Codeforces C. Pluses and Minuses (思維 / 模擬) (Round 90 Rated for Div.2)

傳送門

題意: 實現以下僞代碼
在這裏插入圖片描述
分析以上僞代碼得兩種情況:

  • 當cur < 0時會break當前for循環,然後cur ++,重新開始
  • 當cur始終 > 0時會跑完內部循環,最後終止程序

在這裏插入圖片描述

思路:

  • 分析易得若最開始cur始終 > 0則萬事大吉,但若過程中遇見n次cur < 0就需要重新循環n幾次,顯然時間複雜度就高了。
  • 我們可以用數組a來記錄字符串s的前綴和,並用sum數組記錄每次cur < 0的位置,用tmp記錄上一次cur < 0時的前一位置的前綴和並不斷更新
  • cur會在每個sum[i]位置重新開始,而該位置的前綴和爲b[i],然後每次res可直接加上每次重新開始的位置的前綴和*經過該位置的次數

代碼實現:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 1e6 + 5;

int t, a[N], b[N], sum[N];
char s[N];

signed main()
{
    IOS;

    cin >> t;
    while(t --){
        cin >> s + 1;
        int len = strlen(s + 1);
        int res = 0, tt = 0, tmp = -1;
        a[0] = b[1] = sum[1] = 0;
        for(int i = 1; i <= len; i ++){
            if(s[i] == '+') a[i] = a[i - 1] + 1;
            else a[i] = a[i - 1] - 1;
            if(a[i] <= tmp){
                b[++ tt] = a[i];
                sum[tt] = i;
                tmp = a[i] - 1;
            }
        }
        //res 加上第一次和最後一次循環的次數
        res += (-1 * b[1]) * sum[1] + len;
        for(int i = 2; i <= tt; i ++){
            //負數是小數減大數才爲正
            int cur = b[i - 1] - b[i];
            res += cur * sum[i];
        }
        cout << res << endl;
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章