Gym - 101164C - Castle KMP
题目链接:传送门
题解:
利用KMP的fail失配数组,快速找到当前后缀与前缀的公共前缀点
#include<bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:102400000,102400000") #define ls i<<1 #define rs ls | 1 #define pii pair<int,int> #define MP make_pair typedef long long LL; typedef unsigned long long ULL; const long long INF = 1e18+1LL; const double pi = acos(-1.0); const int N = 2e6+10, M = 1e3+20,inf = 2e9; int fail[N],vis[N],n,Q,cnt,op[N],QQ[N]; char a[N],b[N],ch[N][3]; int sum[N]; void build_fail() { memset(fail,-1,sizeof(fail)); int j = -1; for(int i = 1; i < cnt; ++i) { while(j!=-1&&b[j+1]!=b[i]) j = fail[j]; if(b[j+1] == b[i]) j++; fail[i] = j; } } int len[N]; int main() { scanf("%d%d",&n,&Q); scanf("%s",a); for(int i = 0; i < n; ++i) b[i] = a[i]; cnt = n; len[0] = n; for(int i = 1; i <= Q; ++i) { scanf("%d",&op[i]); len[i] = len[i-1]; if(op[i] == 1) { scanf("%s",ch[i]); b[cnt++] = ch[i][0]; len[i]+=1; } else if(op[i] == 2) QQ[cnt-1] = 1; } build_fail(); for(int i = 0; i < cnt; ++i) { sum[i] = QQ[i]; if(fail[i]!=-1) { sum[i] += sum[fail[i]]; } } int ccnt = n; for(int i = 1; i <= Q; ++i) { if(op[i] == 1) { ccnt++; } else if(op[i] == 2) { vis[ccnt-1] = 1; } else if(op[i] == 3) { int ret = 0; if(vis[ccnt-1]) ret = sum[ccnt-1]; else ret = sum[ccnt-1] - QQ[ccnt-1]; printf("%d\n",ret); } } return 0; }