Educational Codeforces Round 90 (Rated for Div. 2) C. Pluses and Minuses(题解)

You are given a string s consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode:

res = 0
for init = 0 to inf
    cur = init
    ok = true
    for i = 1 to |s|
        res = res + 1
        if s[i] == '+'
            cur = cur + 1
        else
            cur = cur - 1
        if cur < 0
            ok = false
            break
    if ok
        break

Note that the inf denotes infinity, and the characters of the string are numbered from 1 to |s|.

You have to calculate the value of the res after the process ends.

Input
The first line contains one integer t ( 1 ≤ t ≤ 1000 ) t (1≤t≤1000) t(1t1000) — the number of test cases.

The only lines of each test case contains string s ( 1 ≤ ∣ s ∣ ≤ 1 0 6 ) (1≤|s|≤10^6) (1s106)consisting only of characters + and -.

It’s guaranteed that sum of |s| over all test cases doesn’t exceed 1 0 6 10^6 106.

Output
For each test case print one integer — the value of the res after the process ends.
Educational Codeforces Round 90 (Rated for Div. 2) C. Pluses and Minuses(题解)_第1张图片
题意:根据伪代码输出res,cur如果遇见–,则cur减1,cur为负数时,跳出循环,cur初始化cur加一。直到遍历s后,不为负数,输出res.
题解:- - + - : cur=0: s[0] cur=-1 break
cur=1: s[0] cur=0 s[1] cur=-1 break
cur=2: s[0] cur=1 s[1] cur=0 s[2] cur=1 s[3] cur =0
res =7
当cur<0 因此在j前面的都要重新循环 因此res+=j+1(j是从0开始),这时候 cur变为0.

// cf6.22.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include 
#include
#define ll long long
using namespace std;
const int maxn = 1e6+10;
int main()
{
    int  t;
    cin >> t;
    while (t--) {
        string s;
        cin >> s;
        long long  res = 0;//int 会爆 注意
        int cur=0;
        for (int j = 0; j < s.size(); j++)
           {
              // res += 1;
               if (s[j] == '+') {
                   cur += 1;
               }
               else {
                   cur -= 1;
               }
               if (cur < 0) {
                   res += j + 1;//j是从0开始的所以加一
                   cur = 0;
               }
               
           }
        cout << res+s.size() << endl;//res是未到终点前的遍历,s.size()是最后一次到终点的遍历
    }
}



你可能感兴趣的:(Educational Codeforces Round 90 (Rated for Div. 2) C. Pluses and Minuses(题解))