///题意: 求一个串至少出现k次的最长重复子串的长度,可重叠 #include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <cstdlib> #define MAXN 22222 using namespace std; int r[MAXN]; int wa[MAXN], wb[MAXN], wv[MAXN], tmp[MAXN],a[MAXN];; int sa[MAXN]; //index range 1~n value range 0~n-1 int cmp(int *r, int a, int b, int l) { return r[a] == r[b] && r[a + l] == r[b + l]; } void da(int *r, int *sa, int n, int m) { int i, j, p, *x = wa, *y = wb, *ws = tmp; ///对r中长度为1的子串进行基数排序 for (i = 0; i < m; i++) ws[i] = 0; for (i = 0; i < n; i++) ws[x[i] = r[i]]++; for (i = 1; i < m; i++) ws[i] += ws[i - 1]; for (i = n - 1; i >= 0; i--) sa[--ws[x[i]]] = i; ///对r中长度为j的子串进行基数排序 for (j = 1, p = 1; p < n; j *= 2, m = p) { for (p = 0, i = n - j; i < n; i++) y[p++] = i; for (i = 0; i < n; i++) if (sa[i] >= j) y[p++] = sa[i] - j; for (i = 0; i < n; i++) wv[i] = x[y[i]]; for (i = 0; i < m; i++) ws[i] = 0; for (i = 0; i < n; i++) ws[wv[i]]++; for (i = 1; i < m; i++) ws[i] += ws[i - 1]; for (i = n - 1; i >= 0; i--) sa[--ws[wv[i]]] = y[i]; for (swap(x, y), p = 1, x[sa[0]] = 0, i = 1; i < n; i++) x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1 : p++; } } int rank[MAXN]; //index range 0~n-1 value range 1~n int height[MAXN]; //index from 1 (height[1] = 0) void calheight(int *r, int *sa, int n) { int i, j, k = 0; for (i = 1; i <= n; ++i) rank[sa[i]] = i; for (i = 0; i < n; height[rank[i++]] = k) for (k ? k-- : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; ++k); return; } int check(int mid,int n,int k) { for(int sum=1,i =0; i <= n; i++) { if(height[i] >= mid){ sum++; if(sum>=k) return 1; }else sum=1; } return 0; } int main() { int n,k; //freopen("//media/学习/ACM/input.txt","r",stdin); while(scanf("%d%d", &n,&k) != EOF) { for(int i = 0; i < n; i++) scanf("%d", &a[i]),r[i] =a[i]; r[n] = 0; da(r, sa, n + 1, MAXN); calheight(r, sa, n); int low =0, high = n, ans = -1; while(low <= high) { int mid = (low + high) >> 1; if(check(mid, n,k)) { low = mid + 1; ans = max(ans, mid); } else high = mid - 1; } printf("%d\n",ans); } return 0; }
或者 利用KMP 的next性质 水过~~~~~~~~~~~
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> int next[1000100]; char s[1000100]; void get_next(int n) { int i=0; next[i]=-1; int j=next[0]; while(i<=n) { if(j==-1 || s[i]==s[j]) { i++; j++; next[i]=j; } else j = next[j]; } } int main() { scanf("%s",s); while(true) { if(s[0]=='.') break; int len = strlen(s); get_next(len); int t = next[len]; if(len%(len-t)==0) printf("%d/n", len/(len-t)); else printf("%d/n",1); memset(s,0,sizeof(0)); memset(next,0,sizeof(0)); scanf("%s",s); } }