# abc272_f Two Strings (后缀数组)

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int N = 1000010;

char s[N];
int n, sa[N], rk[N], oldrk[N << 1], id[N], px[N], cnt[N];

// px[i] = rk[id[i]]（用于排序的数组所以叫 px）

bool cmp(int x, int y, int w) {
return oldrk[x] == oldrk[y] && oldrk[x + w] == oldrk[y + w];
}
int suf[N];
int main() {
int i, m = 300, p, w; // m是基数排序的值域
scanf("%d", &n);
scanf("%s", s + 1);

for ( int i = n + 1; i <= n << 1; ++ i ) s[i] = s[i - n];
s[n * 2 + 1] = '#';
for ( int i = n * 2 + 2; i <= n * 2 + 1 + n; ++ i ) scanf(" %c", &s[i]);
int tmp = n; n = n * 3 + 1;
for ( int i = n + 1; i <= n + tmp; ++ i ) s[i] = s[i - tmp];
n += tmp;
s[n + 1] = '|'; ++ n;
for (i = 1; i <= n; ++i) {
++cnt[rk[i] = s[i]];
}
for (i = 1; i <= m; ++i) cnt[i] += cnt[i - 1];
for (i = n; i >= 1; --i) sa[cnt[rk[i]]--] = i;

for (w = 1;; w <<= 1, m = p) {  // m=p 就是优化基数排序值域
for (p = 0, i = n; i > n - w; --i) id[++p] = i; //计算按第二关键字排序下的第一关键字id[i]
for (i = 1; i <= n; ++i)
if (sa[i] > w) id[++p] = sa[i] - w;
memset(cnt, 0, sizeof(cnt));
for (i = 1; i <= n; ++i) ++cnt[px[i] = rk[id[i]]]; //在第二排的顺序的排第一编号
for (i = 1; i <= m; ++i) cnt[i] += cnt[i - 1];
for (i = n; i >= 1; --i) sa[cnt[px[i]]--] = id[i];
memcpy(oldrk, rk, sizeof(rk));
for (p = 0, i = 1; i <= n; ++i) // 去重
rk[sa[i]] = cmp(sa[i], sa[i - 1], w) ? p : ++p;
if (p == n) { //没有相同的，就确定出顺序了
for (int i = 1; i <= n; ++i) sa[rk[i]] = i;
break;
}
}

for ( int i = 1; i <= n; ++ i ) {
if(sa[i] > tmp * 2 + 1 && sa[i] <= tmp * 2 + 1 + tmp ) ++ suf[i];
}
long long ans = 0;
for (i = n; i >= 1; --i) {
suf[i] += suf[i + 1];

}

for ( int i = 1; i <= n; ++ i ) {
if(sa[i] <= tmp) ans += suf[i];
}
cout << ans << '\n';
return 0;
}
posted @ 2022-10-09 09:42  qingyanng  阅读(137)  评论(0编辑  收藏  举报