【POJ3261】Milk Patterns【后缀数组】【二分】

似乎是后缀数组的例题?

二分答案ans,将不小于ans的height分组,判断是否有一组个数大于k即可。


听说数字并不是非常大,所以直接把字符集大小设小了。当然也可以离散化。


#include 
#include 

using namespace std;

const int maxn = 20005, maxm = 20005, M = 20000;

int num[maxn], sa[maxn], rank[maxn], height[maxn];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

int wa[maxn], wb[maxn], wv[maxn], cnt[maxm];
void SA(int *r, int n, int m) {
	int *x = wa, *y = wb;
	for(int i = 0; i < m; i++) cnt[i] = 0;
	for(int i = 0; i < n; i++) cnt[x[i] = r[i]]++;
	for(int i = 1; i < m; i++) cnt[i] += cnt[i - 1];
	for(int i = n - 1; i >= 0; i--) sa[--cnt[x[i]]] = i;
	for(int j = 1; j < n; j <<= 1) {
		int p = 0;
		for(int i = n - j; i < n; i++) y[p++] = i;
		for(int i = 0; i < n; i++) if(sa[i] >= j) y[p++] = sa[i] - j;
		for(int i = 0; i < n; i++) wv[i] = x[y[i]];
		for(int i = 0; i < m; i++) cnt[i] = 0;
		for(int i = 0; i < n; i++) cnt[wv[i]]++;
		for(int i = 1; i < m; i++) cnt[i] += cnt[i - 1];
		for(int i = n - 1; i >= 0; i--) sa[--cnt[wv[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] + j] == y[sa[i] + j] ? p - 1 : p++;
		if(p >= n) break;
		m = p;
	}
}

void calcHeight(int *r, int n) {
	int i, j, k;
	for(i = j = k = 0; i < n; height[rank[i++]] = k)
		for(k ? k-- : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; k++);
}

int n, k;

bool check(int x) {
	int i = 1;
	while(1) {
		for(; i <= n && height[i] < x; i++);
		if(i > n) break;
		int cnt = 1;
		for(; i <= n && height[i] >= x; cnt++, i++);
		if(cnt >= k) return 1;
	}
	return 0;
}
		
int main() {
	n = iread(); k = iread();
	for(int i = 0; i < n; i++) num[i] = iread(); num[n] = 0;

	SA(num, n + 1, M);
	for(int i = 0; i <= n; i++) rank[sa[i]] = i;
	calcHeight(num, n);
	
	int l = 1, r = n;
	while(l <= r) {
		int mid = l + r >> 1;
		if(check(mid)) l = mid + 1;
		else r = mid - 1;
	}
	
	printf("%d\n", r);

	return 0;
}


你可能感兴趣的:(二分,后缀数组)