跳到正文

题解

题解:CF1373C Pluses and Minuses

Owenzjg约 1 分钟
原文
文章信息与版本

文章信息

发布
2026年10月13日
收录
2026年10月14日
更新
2026年11月7日
篇幅
约 1 分钟
获赞
1
题目
CF1373C

版本

  1. v2当前
  2. v1

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

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

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

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

C++
#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 排版。

原文