题目大意:(文末有原题)
给出一个有'+' '-'组成的字符串,读伪代码写程序;
res = 0 for init = 0 to inf(0到正无穷,其实就是判断条件为1) cur = init ok = true for i = 1 to |s| res = res + 1 (每进入一次循环,res++) if s[i] == '+' cur = cur + 1 else cur = cur - 1 if cur < 0 (如果cur<0会跳出) ok = false break if ok (如果cur到最后>=0,就出循环) break要求输出跳出循环后res的值,即循环多少次,能够使cur通过一轮循环后>=0(cur每次从cur+1开始);
思路:(按照伪代码暴力写下来程序会TLE)
其实就是输出能够进行多少次循环,因为如果此步>0,就会进行下一步,所以只有当遇到<0,才会再次从头开始循环,所以我们只需记录每一次小于0,需要进行几步,并求出最多能走几步而不跳出循环,此时,再循环一次,就会直接出循环;所以,我们只需将这些步数加起来再加上字符串长度(最后一次直接从头走到尾)得到的就是循环次数;
代码:
#include <iostream> #include <cstring> #include <map> using namespace std; typedef long long ll; const ll maxn = 1e6 + 10; char c[maxn]; ll v[maxn], vis[maxn]; int main() { int t; cin >> t; while(t--) { ll x = 0; cin >> c; map<ll, ll> m; ll s = 0; ll min = 0; ll len = strlen(c); for(ll i = 0; i < len; i++) { if(c[i] == '+') s++; else s--; if(m.count(s) == 0) m[s] = i + 1; //记录小于0的位置,因为小于0时的位置就是执行到此处 res增加的数 当不小于0就会继续往后运行; if(s < min) min = s; //当达到min,再执行一次就会直接出循环, } ll ans = 0; for(ll i = 0; i > min; i--) ans += m[i - 1]; ans += len; cout << ans << endl; } return 0; }题目:
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 breakNote 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.
输入:
The first line contains one integer t (1≤t≤1000) — the number of test cases.
The only lines of each test case contains string s (1≤|s|≤10^6) consisting only of characters + and -.
It's guaranteed that sum of |s| over all test cases doesn't exceed 10^6.
输出:
For each test case print one integer — the value of the res after the process ends.
样例:
Input:
3 --+- --- ++--+-
Output:
7 9 6