跳到正文

题解

题解:P13677 [GCPC 2023] Loop Invariant

Water_Lemon约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年8月9日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟
题目
P13677

版本

  1. v1当前

先用前缀和统计(和)刚好匹配时的数组下标,依次使用 hash 判断字符串是否相同即可。

C++
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull BASE = 1145;
ull h[2000010],p[2000010],k[2000010];
int a[2000010],tot;
ull Hash(int l, int r) {
    return h[r+1]-h[l]*p[r-l+1];
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    string s;
    cin>>s;
    int n=s.size();
    for (int i=1;i<=n;i++){
        a[i]=a[i-1]+(s[i-1]=='('?1:-1);
    }
    if (a[n]){
        cout<<"no"<<'\n';
        return 0;
    }
    int minn=0x3f3f3f3f;
    for(int i=0;i<n;i++) minn=min(minn,a[i]);
    for (int i=0;i<n;i++){
        if (a[i]==minn) {
            k[++tot]=i;
        }
    }
    string ss=s+s;
    int len=2*n;
    p[0]=1;
    for (int i=1;i<=len;i++){
        p[i]=p[i-1]*BASE;
        h[i]=h[i-1]*BASE+ss[i-1];
    }
    ull hash_s=Hash(0,n-1);
    for (int i : k){
        ull hash_i=Hash(i,i+n-1);
        if (hash_i!=hash_s){
            cout<<ss.substr(i, n)<<endl;
            exit(0);
        }
    }
    cout<<"no"<<endl;
    return 0;
}
原文