[AHOI2013]差异

嘟嘟嘟


第一眼肯定是SAM,然后觉得前缀不好做,就翻过来变成后缀好了。
这样就是所有前缀的最长公共后缀之和。
然后还得知道,parent树上两点的最长公共后缀就是lca。
式子不要拆开,定义每一条边的边权就是\(len[fa] - len[p]\),那么相当于求两点之间的路径之和。
考虑每一条边的贡献,就是\(siz[now] * (n - siz[now])\)。为什么不是树的总结点数而是\(n\)呢?因为我们求的是所有前缀,不是所有子串,最多就只有\(n\)个前缀。
然后乘上边权加到答案里即可。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 5e5 + 5;
inline ll read()
{
	ll ans = 0;
	char ch = getchar(), last = ' ';
	while(!isdigit(ch)) last = ch, ch = getchar();
	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
	if(last == '-') ans = -ans;
	return ans;
}
inline void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}

int n;
char s[maxn];
struct Sam
{
	int las, cnt;
	int tra[maxn << 1][30], len[maxn << 1], link[maxn << 1], siz[maxn << 1];
	In void init() {link[las = cnt = 0] = -1;}
	In void insert(int c)
	{
		int now = ++cnt, p = las;
		len[now] = len[las] + 1; siz[now] = 1;
		while(~p && !tra[p][c]) tra[p][c] = now, p = link[p];
		if(p == -1) link[now] = 0;
		else
		{
			int q = tra[p][c];
			if(len[q] == len[p] + 1) link[now] = q;
			else
			{
				int clo = ++cnt;
				memcpy(tra[clo], tra[q], sizeof(tra[q]));
				len[clo] = len[p] + 1;
				link[clo] = link[q], link[q] = link[now] = clo;
				while(~p && tra[p][c] == q) tra[p][c] = clo, p = link[p];
			}
		}
		las = now;
	}
	int bra[maxn << 1], pos[maxn << 1];
	In ll dfs()
	{
		for(int i = 1; i <= cnt; ++i) ++bra[len[i]];
		for(int i = 1; i <= cnt; ++i) bra[i] += bra[i - 1];
		for(int i = 1; i <= cnt; ++i) pos[bra[len[i]]--] = i;
		ll ret = 0;
		for(int i = cnt; i; --i)
		{
			int now = pos[i], fa = link[now];
			siz[fa] += siz[now];
			ret += 1LL * (len[now] - len[fa]) * siz[now] * (n - siz[now]);
		}
		return ret;
	}
}S;

int main()
{
	scanf("%s", s);	
	n = strlen(s); reverse(s, s + n);
	S.init();
	for(int i = 0; i < n; ++i) S.insert(s[i] - 'a');
	write(S.dfs()), enter;
	return 0;
}
posted @ 2019-02-28 17:02  mrclr  阅读(201)  评论(0编辑  收藏  举报