小Hi平时的一大兴趣爱好就是演奏钢琴。我们知道一个音乐旋律被表示为长度为 N 的数构成的数列。小Hi在练习过很多曲子以后发现很多作品中的旋律有重复的部分。
我们把一段旋律称为(k,l)-重复的,如果它满足由一个长度为l的字符串重复了k次组成。 如旋律abaabaabaaba是(4,3)重复的,因为它由aba重复4次组成。
小Hi想知道一部作品中k最大的(k,l)-重复旋律。
题意:求长循环子串
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 5; struct SA { int dp[maxn][20], sa[maxn], rak[maxn]; int tx[maxn], height[maxn], lg[maxn]; int n, m, p; char s[maxn]; struct node { int x, y, id; }a[maxn], b[maxn]; void rsort() { for (int i = 1; i <= m; i++) tx[i] = 0; for (int i = 1; i <= n; i++) tx[a[i].y]++; for (int i = 1; i <= m; i++) tx[i] += tx[i - 1]; for (int i = 1; i <= n; i++) b[tx[a[i].y]--] = a[i]; for (int i = 1; i <= m; i++) tx[i] = 0; for (int i = 1; i <= n; i++) tx[b[i].x]++; for (int i = 1; i <= m; i++) tx[i] += tx[i - 1]; for (int i = n; i >= 1; i--) a[tx[b[i].x]--] = b[i]; } void ssort() { rsort();p = 0; for (int i = 1; i <= n; i++) { if (a[i].x != a[i - 1].x || a[i].y != a[i - 1].y) ++p; rak[a[i].id] = p; } for (int i = 1; i <= n; i++) { a[i].x = rak[i]; a[i].id = sa[rak[i]] = i; a[i].y = 0; } m = p; } void solve() { m = maxn - 1; for (int i = 1; i <= m; i++) { a[i].x = a[i].y = s[i];a[i].id = i; } ssort(); for (int j = 1; j <= n; j <<= 1) { for (int i = 1; i + j <= n; i++) a[i].y = a[i + j].x; ssort(); if (p == n) break; } get_Height(); } void get_Height() { int k = 0; for (int i = 1; i <= n; i++) { if (k) k--; int j = sa[rak[i] - 1]; while (i + k <= n && j + k <= n && s[i + k] == s[j + k]) k++; height[rak[i]] = k; } RMQ(); } void RMQ() { for (int i = 2; i <= n; i++) lg[i] = lg[i >> 1] + 1; for (int i = 1; i <= n; i++) dp[i][0] = height[i]; for (int j = 1; j <= lg[n]; j++) { for (int i = 1; i + (1 << j) < n; i++) dp[i][j] = min(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]); } } int lcp(int x, int y) { int l = rak[x], r = rak[y]; if (l > r) swap(l, r); l++;int k = lg[r - l + 1]; return min(dp[l][k], dp[r - (1 << k) + 1][k]); } }sa; int main() { scanf("%s", sa.s + 1); sa.n = strlen(sa.s + 1); sa.solve(); int ans = 1; for (int L = 1; L <= sa.n; L++) { for (int i = 1; i + L <= sa.n; i += L) { int R = sa.lcp(i, i + L); ans = max(ans, R / L + 1); if (i != 1) { ans = max(ans, sa.lcp(i - L + R % L, i + R % L) / L + 1); } } } printf("%d\n", ans); return 0; }