zoukankan      html  css  js  c++  java
  • HDU 2222 (AC自动机)

    Problem : 给若干个模式串,询问目标串中出现了多少个模式串。
    **Solution : **复习了一下AC自动机。需要注意AC自动机中的fail,和next的含义。fail指向了一个最长的与当前匹配出具有相同后缀的一个前缀节点,next用来转移下一个字符,指向最远可以匹配的位置。另外,在目标串匹配时,需要用一个temp指针不断经过fail指针向前跳转,所有经过的节点都是符合的。

    #include <iostream>
    #include <cstring>
    #include <queue>
    using namespace std;
    
    const int N = 500008;
    struct AC_Automan
    {
    	int next[N][26];
    	int fail[N];
    	int cnt[N];
    	int root, tot;
    	int newnode()
    	{
    		for (int i = 0; i < 26; ++i) next[tot][i] = -1;
    		fail[tot] = -1;
    		cnt[tot] = 0;
    		return tot++;
    	}
    	void clear()
    	{
    		tot = 0;
    		root = newnode();
    	}
    	void insert(const string &s)
    	{
    		int p = root;
    		for (int i = 0, len = s.length(); i < len; ++i)
    		{
    			if (next[p][s[i] - 'a'] == -1) next[p][s[i] - 'a'] = newnode();
    			p = next[p][s[i] - 'a'];
    		}
    		++cnt[p];
    	}
    	void build()
    	{
    		queue <int> Q;
    		Q.push(root);
    		while (!Q.empty())
    		{
    			int p = Q.front(); Q.pop();
    			for (int i = 0; i < 26; ++i)
    			{
    				if (~next[p][i])
    				{
    					if (p == root) fail[next[p][i]] = root;
    					else fail[next[p][i]] = next[fail[p]][i];
    					Q.push(next[p][i]);
    				}
    				else
    				{	
    					if (p == root) next[p][i] = root;
    					else next[p][i] = next[fail[p]][i];
    				}
    			}
    		}
    	}
    	int solve(const string &t)
    	{
    		int p = root, ans = 0;
    		for (int i = 0, len = t.length(); i < len; ++i)
    		{
    			p = next[p][t[i] - 'a'];
    			for (int temp = p; temp != root && cnt[temp] != -1; temp = fail[temp])
    			{
    				ans += cnt[temp];
    				cnt[temp] = -1;
    			}
    		}
    		return ans;
    	}
    }ac;
    
    int main()
    {
    	cin.sync_with_stdio(0);
    	int T; cin >> T;
    	for (int cas = 1; cas <= T; ++cas)
    	{
    		ac.clear();
    		int n; cin >> n;
    		for (int i = 0; i < n; ++i)
    		{
    			string s; cin >> s;
    			ac.insert(s);
    		}
    		ac.build();
    		string t; cin >> t;
    		cout << ac.solve(t) << endl;
    	}
    }
    
    
  • 相关阅读:
    CentOS安装系统时硬盘分区建议
    Linux下的gpt分区
    如何解决Win10账户没有了管理员权限
    redis数据的清空以及回滚
    禅道的作用以及安装
    Java数组的内存图
    Java中的内存划分
    进制
    Java数组
    Java方法的重载(Overload)
  • 原文地址:https://www.cnblogs.com/rpSebastian/p/7191121.html
Copyright © 2011-2022 走看看