HDU 4436 (后缀自动机)

HDU 4436 str2int

Problem : 给若干个数字串,询问这些串的所有本质不同的子串转换成数字之后的和。
Solution : 首先将所有串丢进一个后缀自动机。由于这道题询问的是不同的子串之间的计数,不涉及子串的数目,因此考虑用后缀链即后缀自动机的nt转移数组来做。首先将所有节点进行按照距离大小进行基数排序,然后从小到大枚举每个节点的出边,假设当前点为u,转移到v,那么更新的状态为cnt[v] += cnt[u], sum[v] += sum[u] + cnt[u] * ch,cnt[u]表示的是到达当前节点的子串的数量,sum[u]表示的是该节点所表示的串的答案。
需要注意的是具有前导0的串对答案没有贡献。

#include <string>
#include <iostream>

using namespace std;

const int N = 200008;
const int mo = 2012;

struct Suffix_Automaton
{
	int nt[N][10], fail[N], a[N];
	int last, root, tot;
	int p, q, np, nq;
	int c[N], rk[N], cnt[N], sum[N];

	int newnode(int len)
	{
		for (int i = 0; i < 10; ++i) nt[tot][i] = -1;
		fail[tot] = -1; a[tot] = len;
		c[tot] = rk[tot] = cnt[tot] = sum[tot] = 0;
		return tot++;
	}
	void clear()
	{
		tot = 0;
		last = root = newnode(0);
	}
	void insert(int ch)
	{
		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 < 10; ++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;
			}
		}
	}
	void solve()
	{
		for (int i = 0; i < tot; ++i) c[a[i]]++;
		for (int i = 1; i < tot; ++i) c[i] += c[i - 1];
		for (int i = 0; i < tot; ++i) rk[--c[a[i]]] = i;
		cnt[root] = 1;
		for (int i = 0; i < tot; ++i)
		{
			int u = rk[i];
			for (int j = 0; j < 10; ++j)
				if (~nt[u][j])
				{
					if (i == 0 && j == 0) continue;
					int v = nt[u][j];
					cnt[v] += cnt[u ];
					sum[v] += sum[u] * 10 + j * cnt[u];
					sum[v] %= mo;
				}
		}
		int ans = 0;
		for (int i = 0; i < tot; ++i)
		{
			ans += sum[i];
			ans %= mo;
		}
		cout << ans << endl;
	}

}sam;

int main()
{
	cin.sync_with_stdio(0);
	int n;
	while (cin >> n)
	{
		string s; 
		sam.clear();
		for (int i = 1; i <= n; ++i)
		{
			cin >> s;
			sam.last = 0;
			for (int j = 0, len = s.length(); j < len; ++j)
				sam.insert(s[j] - '0');
		}
		sam.solve();
	}
}
原文地址:https://www.cnblogs.com/rpSebastian/p/7230665.html