SP694 DISUBSTR


/*
统计每个节点的max和min, 然后求和即可 
min = max[fa] + 1

*/
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#define ll long long 
#define M 6010
#define mmp make_pair
using namespace std;
int read()
{
	int nm = 0, f = 1;
	char c = getchar();
	for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
	for(; isdigit(c); c = getchar()) nm = nm * 10 + c - '0';
	return nm * f;
}
int t, ch[M][26], len[M], fa[M], cnt, lst;
char s[M];

void insert(int c)
{
	int p = ++cnt, f = lst;
	len[p] = len[f] + 1; 
	lst = p;
	while(f && !ch[f][c]) ch[f][c] = p, f = fa[f];
	if(!f) 
	{
		fa[p] = 1;
		return;
	}
	int q = ch[f][c], nq = ++cnt;
	if(len[f] + 1 == len[q])
	{
		fa[p] = q;
		cnt--;
		return;
	}
	len[nq] = len[f] + 1;
	fa[nq] = fa[q];
	fa[q] = fa[p] = nq;
	memcpy(ch[nq], ch[q], sizeof(ch[nq]));
	while(f && ch[f][c] == q) ch[f][c] = nq, f = fa[f];
}
	
void init()
{
	cnt = lst = 1;
	memset(ch, 0, sizeof(ch));
	memset(len, 0, sizeof(len));
	memset(fa, 0, sizeof(fa));
}

int main()
{
	t = read();
	while(t--)
	{
		init();
		scanf("%s", s + 1);
		int l = strlen(s + 1);
		for(int i = 1; i <= l; i++) insert(s[i] - 'A');
		int ans = 0;
		for(int i = 1; i <= cnt; i++) ans += len[i] - len[fa[i]];		
		cout << ans << "
";
	}
	return 0;
}
原文地址:https://www.cnblogs.com/luoyibujue/p/10596515.html