【LG4248】[AHOI2013]差异

【LG4248】[AHOI2013]差异

题面

洛谷

题解

后缀数组版做法戳我

我们将原串\(reverse\),根据后缀自动机的性质,两个后缀的\(lcp\)一定是我们在反串后两个前缀的\(lca\)

那么原式不就是求树上两两点对的距离和,

树上一条边的权值可以通过差分求出,就是\(i.len-i.fa.len\)

然后就统计每一条边的贡献就行了。

感觉少个log效率还跟sa差不多啊

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring> 
#include <cmath> 
#include <algorithm>
using namespace std; 
const int MAX_N = 5e5 + 5; 
struct Node { int ch[26], len, fa; } t[MAX_N << 1]; 
int lst = 1, tot = 1, size[MAX_N << 1]; 
void extend(int c) { 
	int np = ++tot; 
	t[lst].ch[c] = np; 
	t[np].len = t[lst].len + 1; 
	int p = t[lst].fa; lst = np;
	while (p && !t[p].ch[c]) t[p].ch[c] = np, p = t[p].fa; 
	if (!p) t[np].fa = 1;
	else { 
		int q = t[p].ch[c];
		if (t[q].len == t[p].len + 1) t[np].fa = q; 
		else {
			int nq = ++tot; 
			t[nq] = t[q]; 
			t[nq].len = t[p].len + 1, t[q].fa = t[np].fa = nq; 
			while (p && t[p].ch[c] == q) t[p].ch[c] = nq, p = t[p].fa; 
		} 
	} 
	size[np] = 1; 
} 
int N, bln[MAX_N << 1], A[MAX_N << 1]; 
char a[MAX_N]; 
int main () { 
#ifndef ONLINE_JUDGE 
    freopen("cpp.in", "r", stdin); 
#endif 
	scanf("%s", a + 1); N = strlen(a + 1); 
	for (int i = 1; i <= N; i++) extend(a[N - i + 1] - 'a'); 
	for (int i = 1; i <= tot; i++) bln[t[i].len]++; 
	for (int i = 1; i <= tot; i++) bln[i] += bln[i - 1]; 
	for (int i = 1; i <= tot; i++) A[bln[t[i].len]--] = i;
	long long ans = 0; 
    for (int i = tot; i; i--) { 
		int x = A[i]; 
		size[t[x].fa] += size[x]; 
		ans += 1ll * (t[x].len - t[t[x].fa].len) * size[x] * (N - size[x]); 
	} 
	printf("%lld\n", ans); 
    return 0; 
} 
posted @ 2019-03-25 22:55  heyujun  阅读(176)  评论(0编辑  收藏  举报