HiHocoder1419 : 后缀数组四·重复旋律4&[SPOJ]REPEATS:Repeats

题面

Hihocoder
Vjudge

Sol

题目的提示说的也非常好
我对求\(LCP(P - L + len \% l, P + len \% L)\)做补充
\(len=LCP(P, P + L)\)
为什么只要求\(LCP(P - L + len \% l, P + len \% L)\)呢?
考虑在\(P - L + len \% l\)右边到\(P\)之间,它不比这里的重复次数大
考虑在\(P - L + len \% l\)左边到\(P-1\)之间,一样的它也是不增的

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(100010);

int n, a[_], sa[_], rk[_], y[_], height[_], t[_], vis[_];
int st[20][_], lg[_];
char s[_];

IL bool Cmp(RG int i, RG int j, RG int k){  return y[i] == y[j] && y[i + k] == y[j + k];  }

IL void Sort(){
	RG int m = 30;
	for(RG int i = 1; i <= n; ++i) ++t[rk[i] = a[i]];
	for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
	for(RG int i = n; i; --i) sa[t[rk[i]]--] = i;
	for(RG int k = 1; k <= n; k <<= 1){
		RG int l = 0;
		for(RG int i = n - k + 1; i <= n; ++i) y[++l] = i;
		for(RG int i = 1; i <= n; ++i) if(sa[i] > k) y[++l] = sa[i] - k;
		for(RG int i = 0; i <= m; ++i) t[i] = 0;
		for(RG int i = 1; i <= n; ++i) ++t[rk[y[i]]];
		for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
		for(RG int i = n; i; --i) sa[t[rk[y[i]]]--] = y[i];
		swap(rk, y); rk[sa[1]] = l = 1;
		for(RG int i = 2; i <= n; ++i) rk[sa[i]] = Cmp(sa[i - 1], sa[i], k) ? l : ++l;
		if(l >= n) break;
		m = l;
	}
	for(RG int i = 1, j = 0; i <= n; ++i){
		j = max(0, j - 1);
		while(a[j + i] == a[sa[rk[i] - 1] + j]) ++j;
		height[rk[i]] = j;
	}
}

IL int LCP(RG int xx, RG int yy){
	xx = rk[xx]; yy = rk[yy];
	if(xx > yy) swap(xx, yy);
	++xx;
	RG int l = lg[yy - xx + 1];
	return min(st[l][xx], st[l][yy - (1 << l) + 1]);
}

IL int Calc(){
	RG int ans = 0;
	for(RG int l = 1; l <= n; ++l)
		for(RG int i = 1; i + l <= n; i += l){
			RG int len = LCP(i, i + l);
			ans = max(ans, len / l + 1);
			if(i >= l - len % l) ans = max(ans, LCP(i - l + len % l, i + len % l) / l + 1);
		}
	return ans;
}

int main(RG int argc, RG char* argv[]){
	scanf(" %s", s + 1);
	n = strlen(s + 1);
	for(RG int i = 1; i <= n; ++i) a[i] = s[i] - 'a' + 1;
	for(RG int i = 2; i <= n; ++i) lg[i] = lg[i >> 1] + 1;
	Sort();
	for(RG int i = 1; i <= n; ++i) st[0][i] = height[i];
	for(RG int i = 1; i <= lg[n]; ++i)
		for(RG int j = 1; j + (1 << i) - 1 <= n; ++j)
			st[i][j] = min(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
	printf("%d\n", Calc());
    return 0;
}


posted @ 2018-01-24 22:15  Cyhlnj  阅读(152)  评论(1编辑  收藏  举报