题解:CF1373C Pluses and Minuses

· · 题解

先理解一下伪代码是干什么的。

可以理解为 cnt 初始在 i=0 的位置是 0,从前往后 + 就是 +1,- 就是 -1,如果 cnt<0 了就把初始位置的值 +1,统计全部移动的距离。

可以发现 cnt<0 了相当于移动的距离加上现在的位置 i,可以避免这一层循环,从而让复杂度正确。

注意字符串的偏移,以及要开 long long。

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin>>t;
    while(t--){
        string str;
        cin>>str;

        int m=str.size();
        long long cnt=0,ans=m;
        for(int i=0;i<m;i++){
            if(str[i]=='+') cnt++;
            else cnt--;
            if(cnt<0){
                ans=ans+i+1;
                cnt++;
            }
        }

        cout<<ans<<"\n";
    }

    return 0;
}

本文使用 ChatGPT 辅助检查错别字并规范 Markdown、LaTeX 排版。