HDU 4622 (后缀自动机)

HDU 4622 Reincarnation

Problem : 给一个串S(n <= 2000), 有Q个询问(q <= 10000),每次询问一个区间内本质不同的串的个数。
Solution : 由于n只有2000,对串S的每一个左端点建立一遍后缀自动机,暴力计算出所有答案的值。。。

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 2008;
const int INF = 2000000008;

struct suffix_automanon
{
	int nt[N << 1][26], fail[N << 1], a[N << 1];
	int tot, last, root, tmp;
	int p, q, np, nq;

	int ans[N][N];
	int newnode(int len)
	{
		for (int i = 0; i < 26; ++i) nt[tot][i] = -1;
		fail[tot] = -1; a[tot] = len;
		return tot++;
	}
	void clear()
	{
		tot = tmp = 0;
		root = last = newnode(0);
	}
	void insert(int ch, int l, int r)
	{
		p = last; last = np = newnode(a[p] + 1); 
		for (; ~p && nt[p][ch] == -1; p = fail[p]) nt[p][ch] = np;
		if (p == -1) fail[np] = root;
		else
		{
			q = nt[p][ch];
			if (a[p] + 1 == a[q]) fail[np] = q;
			else
			{
				nq = newnode(a[p] + 1);
				for (int i = 0; i < 26; ++i) nt[nq][i] = nt[q][i];
				fail[nq] = fail[q];
				fail[q] = fail[np] = nq;
				for (; ~p && nt[p][ch] == q; p = fail[p]) nt[p][ch] = nq;
			}
		}
		tmp += a[np] - a[fail[np]];
		ans[l][r] = tmp;
	}		
}sam;

int main()
{
	cin.sync_with_stdio(0);
	int t; cin >> t;
	for (int i = 1; i <= t; ++i)
	{
		string s; cin >> s;
		for (int i = 0, len = s.length(); i < len; ++i)
		{
			sam.clear();
			for (int j = i; j < len; ++j)
				sam.insert(s[j] - 'a', i, j);
		}
		int q;
		cin >> q;
		while (q--)
		{
			int l, r; cin >> l >> r;
			cout << sam.ans[l - 1][r - 1] << endl;
		}
	}
}


posted @ 2017-07-22 20:46  rpSebastian  阅读(147)  评论(0编辑  收藏  举报