Thus, the message contains possibly overlapping repetitions of the same words over and over again. As a result, Ellie turns to you, S.R. Hadden, for help in identifying the gist of the message.
Given an integer m, and a string s, representing the message, your task is to find the longest substring ofs that appears at least m times. For example, in the messagebaaaababababbababbab, the length-5 wordbabab is contained 3 times, namely at positions5, 7 and 12 (where indices start at zero). No substring appearing3 or more times is longer (see the first example from the sample input). On the other hand, no substring appears11 times or more (see example 2).
In case there are several solutions, the substring with the rightmost occurrence is preferred (see example3).
3 baaaababababbababbab 11 baaaababababbababbab 3 cccccc 0
5 12 none 4 2
本题为lrj的白书中Hash求LCP入门题。
方法请参考白书
#include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<functional> #include<iostream> #include<cmath> #include<cctype> #include<ctime> using namespace std; #define For(i,n) for(int i=1;i<=n;i++) #define Fork(i,k,n) for(int i=k;i<=n;i++) #define Rep(i,n) for(int i=0;i<n;i++) #define ForD(i,n) for(int i=n;i;i--) #define RepD(i,n) for(int i=n;i>=0;i--) #define Forp(x) for(int p=pre[x];p;p=next[p]) #define Forpiter(x) for(int &p=iter[x];p;p=next[p]) #define Lson (x<<1) #define Rson ((x<<1)+1) #define MEM(a) memset(a,0,sizeof(a)); #define MEMI(a) memset(a,127,sizeof(a)); #define MEMi(a) memset(a,128,sizeof(a)); #define INF (2139062143) #define F (100000007) #define MAXN (40000+10) typedef long long ll; typedef unsigned long long ull; ll mul(ll a,ll b){return (a*b)%F;} ll add(ll a,ll b){return (a+b)%F;} ll sub(ll a,ll b){return (a-b+(a-b)/F*F+F)%F;} void upd(ll &a,ll b){a=(a%F+b%F)%F;} int n,m; char s[MAXN]; const int x=143; ull H[MAXN],xp[MAXN],hash[MAXN]; int rank[MAXN]; int cmp(const int &a,const int &b) { return hash[a]<hash[b]||(hash[a]==hash[b]&&a<b); } int is_ok(int M) { int pos=-1,c=0; Rep(i,n-M+1) { rank[i]=i;hash[i]=H[i]-H[i+M]*xp[M]; } sort(rank,rank+1+n-M,cmp); //排序 rank[0]--rank[n-m] Rep(i,n-M+1) { if (i==0||hash[rank[i]]^hash[rank[i-1]]) c=0; //是否有以前的‘积累’ c++; if (c>=m) pos=max(pos,rank[i]); } return pos; } int main() { // freopen("la4513.in","r",stdin); // freopen(".out","w",stdout); xp[0]=1; For(i,MAXN-1) xp[i]=xp[i-1]*x; while(scanf("%d%s",&m,s)!=EOF&&m>0) { n=strlen(s); H[n]=0; RepD(i,n-1) H[i]=H[i+1]*x+s[i]-'a'; if (is_ok(1)==-1) printf("none\n"); else { int L=1,R=n,ans=m; while (L<=R) { int M=(L+R)>>1; if (is_ok(M)!=-1) L=M+1,ans=M; else R=M-1; } printf("%d %d\n",ans,is_ok(ans)); } } return 0; }