Educational Codeforces Round 90 (Rated for Div. 2) C. Pluses and Minuses(思维)

Pluses and Minuses

题目大意:(文末有原题)

给出一个有'+' '-'组成的字符串,读伪代码写程序;

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
        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.

输入:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值