题目:http://poj.org/problem?id=3261
题目大意:给你一个字符串,让你输出它的最长的至少k次重复的子串的长度。
思路:先离散一下,然后构造后缀数组,然后二分答案,每次一边扫 height 就行了。
代码如下:
#include<cstdio> #include<cstring> #include<map> #include<algorithm> using namespace std; const int MAXN = 22222; int s[MAXN]; int sa[MAXN],rank[MAXN],height[MAXN]; int t[MAXN],t2[MAXN],c[MAXN]; void get_height(int n) { for(int i = 1;i <= n;i++) rank[sa[i]] = i; int k = 0; for(int i = 0;i < n;i++) { if(k) k--; int j = sa[rank[i]-1]; while(s[i+k] == s[j+k]) k++; height[rank[i]] = k; } } void da(int n,int m) { int *x = t,*y = t2; for(int i = 0;i < m;i++) c[i] = 0; for(int i = 0;i < n;i++) c[x[i] = s[i]]++; for(int i = 1;i < m;i++) c[i] += c[i-1]; for(int i = n-1;i >= 0;i--) sa[--c[x[i]]] = i; for(int k = 1;k <= n;k <<= 1) { int p = 0; for(int i = n-k;i < n;i++) y[p++] = i; for(int i = 0;i < n;i++) if(sa[i] >= k) y[p++] = sa[i] - k; for(int i = 0;i < m;i++) c[i] = 0; for(int i = 0;i < n;i++) c[x[y[i]]]++; for(int i = 1;i < m;i++) c[i] += c[i-1]; for(int i = n-1;i >= 0;i--) sa[--c[x[y[i]]]] = y[i]; swap(x,y); p = 1; x[sa[0]] = 0; for(int i = 1;i < n;i++) x[sa[i]] = y[sa[i-1]] == y[sa[i]] && y[sa[i-1]+k] == y[sa[i]+k] ? p-1 : p++; if(p >= n) break; m = p; } get_height(n-1); } bool flag[MAXN]; int check(int mid,int n,int k) { int cc = 0; memset(flag,0,sizeof(flag)); for(int i = 2;i <= n;i++) { //printf("i = %d,hi = %d\n",i,height[i]); if(height[i] >= mid) { if(flag[i-1] == 0) { flag[i-1] = 1; cc++; } if(flag[i] == 0) { flag[i] = 1; cc++; } } else { cc = 0; memset(flag,0,sizeof(flag)); } if(cc >= k) return 1; } return 0; } int slove(int n,int k) { int l = 1,r = n; int ans = 0; while(l <= r) { int mid = (l+r) >> 1; //printf("l = %d,r = %d,mid = %d\n",l,r,mid); if(check(mid,n,k)) { ans = mid; l = mid+1; } else r = mid - 1; } return ans; } map <int,int> mm; int num[MAXN]; int main() { int n,k; while(~scanf("%d%d",&n,&k)) { mm.clear(); int tot = 1; for(int i = 0;i < n;i++) { scanf("%d",&num[i]); if(!mm[num[i]]) mm[num[i]] = tot++; } for(int i = 0;i < n;i++) s[i] = mm[num[i]]; s[n] = 0; //for(int i = 0;i <= n;i++) //printf("i = %d,si = %d\n",i,s[i]); da(n+1,tot); printf("%d\n",slove(n,k)); } return 0; }