zoukankan      html  css  js  c++  java
  • 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
    ", 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());
    }
    
    
  • 相关阅读:
    记一次文件转码与二进制查看学习
    JAVA线程池 之 Executors (二) 原理分析
    JAVA线程池 之 Executors (一) 简介
    问题:部分mysql版本问题
    Java中一个方法字节码的长度会影响程序并发下的性能?
    AccessController.doPrivileged
    Nginx配置WebService、MySQL、SQL Server、ORACLE等代理
    C# 序列化Json时如何忽略JsonProperty(PropertyName =“ someName”)
    C# 文件上传(另一台服务器的共享目录)
    C# 导入Excel读取图片上传
  • 原文地址:https://www.cnblogs.com/rpSebastian/p/7218632.html
Copyright © 2011-2022 走看看