SPOJ NSUBSTR (后缀自动机)

SPOJ NSUBSTR

Problem : 给一个长度为n的字符串,要求分别输出长度为1~n的子串的最多出现次数。
Solution :首先对字符串建立后缀自动机,在根据fail指针建立出后缀树,对于n个后缀对应的节点打上标记,则每个结点对应的一些子串所出现的次数即为其子树内标记的个数,在后缀树上进行1遍dfs统计,之后根据答案的单调性线性扫描一遍进行统计。

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

const int N = 250008;

struct node
{
	int u, v, nt;
};

struct Suffix_Automaton
{
	int nt[N << 1][26], a[N << 1], fail[N << 1];
	int tot, last, root;
	int p, q, np, nq;
	
	int lt[N << 1], sum;
	node eg[N << 2]; 
	int dp[N << 1], cnt[N << 1];

	void add(int u, int v)
	{ 
		eg[++sum] = (node){u, v, lt[u]}; lt[u] = sum;
		eg[++sum] = (node){v, u, lt[v]}; lt[v] = sum;
	}
	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()
	{
		memset(lt, 0, sizeof(lt));
		tot = last = 0; sum = 0;
		root = newnode(0);
	}
	void insert(int ch)
	{
		p = last; last = np = newnode(a[p] + 1); cnt[np] = 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[np] = fail[q] = nq;
				for (; ~p && nt[p][ch] == q; p = fail[p]) nt[p][ch] = nq;
			}
		}
	}
	void dfs(int u, int fa)
	{
		for (int i = lt[u]; i; i = eg[i].nt)
		{
			int v = eg[i].v;
			if (v != fa)
			{
				dfs(v, u);
				cnt[u] += cnt[v];
			}
		}
		dp[a[u]] = max(dp[a[u]], cnt[u]);
	}
	void solve(int len)
	{
		for (int i = 1; i < tot; ++i) add(fail[i], i);
		dfs(root, -1);
		for (int i = len - 1; i >= 1; i--) dp[i] = max(dp[i], dp[i + 1]);
		for (int i = 1; i <= len; ++i) printf("%d\n", dp[i]);
	}
}sam;

int main()
{
	cin.sync_with_stdio(0);
	sam.clear();
	string s; cin >> s;
	for (int i = 0, len = s.length(); i < len; ++i)
		sam.insert(s[i] - 'a');
	sam.solve(s.length());
}

posted @ 2017-07-21 16:57  rpSebastian  阅读(234)  评论(0编辑  收藏  举报