CodeForces 631D Messenger
$KMP$。
$n=1$和$n=2$的时候可以单独计算。$n>2$时,可以拿字符和数字分别做一次匹配,然后扫描一遍判断一下就可以计算出答案了。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<bitset> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0),eps=1e-6; void File() { freopen("D:\\in.txt","r",stdin); freopen("D:\\out.txt","w",stdout); } template <class T> inline void read(T &x) { char c=getchar(); x=0; while(!isdigit(c)) c=getchar(); while(isdigit(c)) {x=x*10+c-'0'; c=getchar();} } const int maxn=200010; struct X { LL num; int a; }s[maxn],t[maxn]; int lens,lent,n,m; char op[100]; int nx[maxn],f[maxn],g[maxn]; LL a[maxn],b[maxn]; int len1,len2; void get_next() { int j=-1,i=0; nx[0]=-1; while(i<len2) { if(j==-1||b[i]==b[j]) i++, j++, nx[i]=j; else j=nx[j]; } } void kmp(bool x){ get_next(); int i=0,j=0; while(i<len1){ if(j==-1||a[i]==b[j]) i++ ,j++; else j=nx[j]; if(j==len2) { if(x==0) f[i-j+len2]=1; else g[i-j+len2]=1; } } } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { scanf("%s",op); int L=strlen(op); int num=0,sign; for(int j=0;j<=L-3;j++) num=num*10+op[j]-'0'; sign=op[L-1]-'a'+1; if(lens==0||sign!=s[lens-1].a) { s[lens].num=num; s[lens].a=sign; lens++; } else s[lens-1].num+=num; } for(int i=1;i<=m;i++) { scanf("%s",op); int L=strlen(op); int num=0,sign; for(int j=0;j<=L-3;j++) num=num*10+op[j]-'0'; sign=op[L-1]-'a'+1; if(lent==0||sign!=t[lent-1].a) { t[lent].num=num; t[lent].a=sign; lent++; } else t[lent-1].num+=num; } if(lent==1) { LL ans=0; for(int i=0;i<lens;i++) { if(s[i].a!=t[0].a) continue; if(s[i].num<t[0].num) continue; ans=ans+s[i].num-t[0].num+1; } printf("%lld\n",ans); } else if(lent==2) { LL ans=0; for(int i=0;i<lens-1;i++) { if(s[i].a!=t[0].a||s[i+1].a!=t[1].a) continue; if(t[0].num>s[i].num||t[1].num>s[i+1].num) continue; ans++; } printf("%lld\n",ans); } else { for(int i=0;i<lens;i++) a[i]=s[i].a; for(int i=0;i<lent;i++) b[i]=t[i].a; len1=lens,len2=lent; kmp(0); memset(a,0,sizeof a); memset(b,0,sizeof b); for(int i=0;i<lens;i++) a[i]=s[i].num; for(int i=1;i<lent-1;i++) b[i-1]=t[i].num; len1=lens; len2=lent-2; kmp(1); LL ans=0; for(int i=0;i<lens;i++) { if(f[i+1]==0) continue; if(g[i]==0) continue; if(s[i].num<t[lent-1].num) continue; if(s[i-lent+1].num<t[0].num) continue; ans++; } printf("%lld\n",ans); } return 0; }