SPOJ 705 子串个数 后缀数组

依然是论文里的题目…… 其中注意,答案要用LONG LONG保存……被坑了一下然后才过


#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;


const int max_n = 50000 + 10;
char s[max_n];
int slen;
int a[max_n], wa[max_n], wb[max_n], wv[max_n], tub[max_n];
int sa[max_n], height[max_n], rank[max_n];


bool cmp(int *r, int a, int b, int l)
{return r[a] == r[b] && r[a + l] == r[b + l];}

void da(int *r, int *sa, int n, int m)
{
	int i, j, p, *x = wa, *y = wb;
	for (i = 0; i!= m; ++ i)	tub[i] = 0;
	for (i = 0; i != n; ++ i)	tub[x[i] = r[i]] ++;
	for (i = 1; i != m; ++ i)	tub[i] += tub[i - 1];
	for (i = n - 1; i >= 0; -- i)	sa[ -- tub[x[i]]] = i;
	for (j = 1; p != n; m = p, j *= 2)
	{
		for (p = 0, i = n - j; i != n; ++ i)	y[p ++]	= i;
		for (i = 0; i != n; ++ i)	if(sa[i] >= j)	y[p ++] = sa[i] - j;
		for (i = 0; i != n; ++ i)	wv[i] = x[y[i]];
		for (i = 0; i != m; ++ i)	tub[i] = 0;
		for (i = 0; i != n; ++ i)	tub[wv[i]] ++;
		for (i = 1; i != m; ++ i)	tub[i] += tub[i - 1];
		for (i = n - 1; i >= 0; i -- )	sa[-- tub[wv[i]]] = y[i];
		for (swap(x, y), i = 1, p = 1, x[sa[0]] = 0; i != n; ++ i)
			x[sa[i]] = cmp(y, sa[i], sa[i - 1], j) ? p - 1 : p ++;
	}
}

void calheight(int *r, int *sa, int n)
{
	int i, j, k = 0;
	for (i = 1; i <= n; ++ i)	rank[sa[i]] = i;
	for (i = 0; i != n; height[rank[i ++]] = k)
		for (k ? k -- : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; ++ k);
}

void doit()
{
	long long totans = (1LL + slen) * slen / 2LL;
	long long rep = 0;
	for (int i = 1; i <= slen; ++ i)	rep += height[i];
	cout<< totans - rep << endl;
}

int main()
{
	ios::sync_with_stdio(false);
	int tt;
	cin >> tt;
	while (tt--)
	{
		cin>>s;	
		slen = strlen(s);
		for (int i = 0; i  != slen; ++ i)	a[i] = (int)s[i];
//		for (int i = 0; i != slen; ++ i)	cout<<a[i]<<" ";cout<<endl;
		a[slen] = 0;
		da(a, sa, slen + 1, 200);
		calheight(a, sa, slen);
		doit();	
	}
	return 0;
}


你可能感兴趣的:(SPOJ 705 子串个数 后缀数组)