hdu 4333 Revolving Digits 扩展kmp
#include<iostream> #include <cstdio> #include<cstring> using namespace std; const int MM=201000; int next[MM],extand[MM],next2[MM]; char S[MM],T[MM]; void GetNext(const char *T){ int len=strlen(T),a=0; next[0]=len; while(a<len-1 && T[a]==T[a+1]) a++; next[1]=a; a=1; for(int k=2;k<len;k++){ int p=a+next[a]-1,L=next[k-a]; if( (k-1)+L >= p){ int j = (p-k+1)>0 ? (p-k+1) : 0; while(k+j<len && T[k+j]==T[j]) j++; next[k]=j; a=k; } else next[k]=L; } } void GetExtand(const char *S,const char *T){ GetNext(T); int slen=strlen(S),tlen=strlen(T),a=0; int MinLen = slen < tlen ? slen : tlen; while(a<MinLen && S[a]==T[a]) a++; extand[0]=a; a=0; for(int k=1;k<slen;k++){ int p=a+extand[a]-1, L=next[k-a]; if( (k-1)+L >= p){ int j= (p-k+1) > 0 ? (p-k+1) : 0; while(k+j<slen && j<tlen && S[k+j]==T[j]) j++; extand[k]=j; a=k; } else extand[k]=L; } } void getNext(char T[],int len) { int j,k; j=0;k=-1;next2[0]=-1; while(j<len) { if(k==-1 || T[j]==T[k]) next2[++j]=++k; else k=next2[k]; } } int main() { int cas; scanf("%d",&cas); int now=0; while(cas--) { int i; int suml=0,sumr=0,sum=0; now++; scanf("%s",T); strcpy(S,T); strcat(S,T); GetExtand(S,T); int len=strlen(T); for(i=0;i<len;i++) { if(extand[i]>=len) {sum++;continue;} else if(T[extand[i]]>S[extand[i]+i])suml++; else if(T[extand[i]]<S[extand[i]+i]) sumr++; } getNext(T,len); int x=len-next2[len]; int fac=1; if(len%x==0)fac=len/x; printf("Case %d: %d %d %d\n",now,suml/fac,sum/fac,sumr/fac); } return 0; }