Luogu P2743 [USACO5.1]乐曲主题Musical Themes

链接 \(Click\) \(Here\)

人生第一道后缀数组的题目。首先要对输入的串进行差分处理,差分后长度为(\(n - 1\))的相同子段就是原串中长度为\(n\)的相同(可变调)子段。求出来\(height\)以后,二分一个最大不相交重复子段长度,在\(can\_use\)里面维护长度为\(k\)的段划分,判断不相交只要用\(sa\)的差值算一下长度就好。

\(p.s.\)细节真的很多。

#include <bits/stdc++.h>
using namespace std;

const int N = 5010;

int n, m = 255, s[N], sa[N], rk[N], tp[N], _rk[N], bin[N], height[N];

void base_sort () {
	for (int i = 0; i <= m; ++i) bin[i] = 0;
	for (int i = 1; i <= n; ++i) bin[rk[tp[i]]]++;
	for (int i = 1; i <= m; ++i) bin[i] += bin[i - 1];
	for (int i = n; i >= 1; --i) sa[bin[rk[tp[i]]]--] = tp[i];
}

void suffix_sort () {
	for (int i = 1; i <= n; ++i) {
		rk[i] = s[i];
		tp[i] = i;
	}
	base_sort ();
	for (int w = 1; w <= n; w <<= 1) {
		int cnt = 0;
		for (int i = n - w + 1; i <= n; ++i) {
			tp[++cnt] = i;
		}
		for (int i = 1; i <= n; ++i) {
			if (sa[i] > w) {
				tp[++cnt] = sa[i] - w;
			}
		}
		base_sort ();
		memcpy (_rk, rk, sizeof (rk));
	    rk[sa[1]] = cnt = 1;
		for (int i = 2; i <= n; ++i) {
			rk[sa[i]] = _rk[sa[i]] == _rk[sa[i - 1]] && _rk[sa[i] + w] == _rk[sa[i - 1] + w] ? cnt : ++cnt;
		}
		if (cnt == n) break;
		m = cnt;
	}
}

void get_height () {
	int k = 0;
	for (int i = 1; i <= n; ++i) {
		if (k != 0) k = k - 1;
	    int j = sa[rk[i] - 1];
		while (s[i + k] == s[j + k]) {
			k = k + 1;
		}
		height[rk[i]] = k;
	}
}

const int INF = 0x3f3f3f3f;

bool can_use (int k) {
	//是否有长度>=k的不交叉子串
	int max_sa = sa[1], min_sa = sa[1];
	for (int i = 2; i <= n; ++i) {
		if (height[i] >= (k - 1)) {
			//即原串中旋律长度 >= k
			max_sa = max (max_sa, sa[i]);
			min_sa = min (min_sa, sa[i]);
			if (max_sa - min_sa >= k) {
				return true;
			}
		} else {
			max_sa = sa[i];
			min_sa = sa[i];
		}
	}
	return false;
}

int main () {
	cin >> n;
	for (int i = 1; i <= n; ++i) {
		cin >> s[i];
	}
	for (int i = n; i >= 1; --i) {
		s[i] = s[i] - s[i - 1] + 90;
		//把s差分,出现n-1个相同项说明最长为n
	}
	// printf ("str Test   :  "); for (int i = 1; i <= n; ++i) printf ("%3d ", s[i]); putchar ('\n');
	suffix_sort ();
	get_height ();
	// printf ("height Test : "); for (int i = 1; i <= n; ++i) printf ("%3d ", height[i]); printf ("\n");
	int l = 0, r = n;
	while (l < r) {
		// printf ("l = %d, r = %d\n", l, r);
		int mid = (l + r + 1) >> 1;
		if (can_use (mid)) {
			//存在长度 >= mid的不交叉子串
			l = mid;
		} else {
			r = mid - 1;
		}
	}
	if (l < 5) printf ("0\n");
	else printf ("%d\n", l);
}

posted @ 2019-02-25 20:06  maomao9173  阅读(262)  评论(0编辑  收藏  举报