还是一样的,这题是整形数字,也可以转为字符串算法做,用后缀数组,二分以后分组判定就可以了
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ms(i, j) memset(i, j, sizeof i)
#define FN2 "poj3261"
using namespace std;
const int MAXN = 20000 + 5;
int maxi, m, n, k, a[MAXN], tp[MAXN], SA[MAXN], rk[MAXN], height[MAXN], tax[MAXN];
bool cmp(int *f, int i, int k) {return f[SA[i]]==f[SA[i-1]]&&f[SA[i]+k]==f[SA[i-1]+k];}
void build() {
for (int i=0;i<m;i++) tax[i] = 0;
for (int i=0;i<n;i++) tax[rk[i]=a[i]]++;
for (int i=1;i<m;i++) tax[i] += tax[i-1];
for (int i=n-1;i>=0;i--) SA[--tax[rk[i]]] = i;
int p;
for (int k=1;k<=n;k*=2) {
p = 0;
for (int i=n-k;i<n;i++) tp[p++] = i;
for (int i=0;i<n;i++) if (SA[i]>=k) tp[p++] = SA[i] - k;
for (int i=0;i<m;i++) tax[i] = 0;
for (int i=0;i<n;i++) tax[rk[tp[i]]]++;
for (int i=1;i<m;i++) tax[i] += tax[i-1];
for (int i=n-1;i>=0;i--) SA[--tax[rk[tp[i]]]] = tp[i];
swap(rk, tp), p = 0, rk[SA[0]] = 0;
for (int i=1;i<n;i++) rk[SA[i]] = cmp(tp, i, k) ? p : ++p;
if (++p>=n) break;
m = p;
}
}
void getH() {
int k = 0;
for (int i=0;i<n;i++) {
if (k) k--;
int j = SA[rk[i]-1];
while (a[i+k]==a[j+k]) k++;
height[rk[i]] = k;
}
}
void init() {
maxi = 0;
for (int i=0;i<n;i++) scanf("%d", &a[i]), maxi = max(maxi, ++a[i]);//原串可能有0,所以+1,注意
n++, a[n-1] = 0, m = maxi + 1;
}
int used[MAXN];
bool check(int x) {
int tot = 0; ms(used, false);
for (int i=2;i<n;i++) {
if (height[i]<x) {
ms(used, false);
tot = 0;
continue;
}
if (!used[SA[i-1]]) used[SA[i-1]] = true, ++tot;
if (!used[SA[i]]) used[SA[i]] = true, ++tot;
if (tot>=k) return true;
}
return false;
}
void solve() {
build(), getH();
int l = 1, r = n + 1, ans = 0;
while (l<r) {
int mid = (l+r)/2;
if (check(mid)) {
ans = mid;
l = mid + 1;
} else r = mid;
}
printf("%d\n", ans);
}
int main() {
#ifndef ONLINE_JUDGE
freopen(FN2".in","r",stdin);freopen("1.out","w",stdout);
#endif
while(scanf("%d%d", &n, &k)==2) init(), solve();
return 0;
}