hdu 3065 病毒侵襲持續中 AC自動機模板題 ,,一A。

病毒侵襲持續中

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7685    Accepted Submission(s): 2687


Problem Description
小t非常感謝大家幫忙解決了他的上一個問題。然而病毒侵襲持續中。在小t的不懈努力下,他發現了網路中的“萬惡之源”。這是一個龐大的病毒網站,他有着好多好多的病毒,但是這個網站包含的病毒很奇怪,這些病毒的特徵碼很短,而且只包含“英文大寫字符”。當然小t好想好想爲民除害,但是小t從來不打沒有準備的戰爭。知己知彼,百戰不殆,小t首先要做的是知道這個病毒網站特徵:包含多少不同的病毒,每種病毒出現了多少次。大家能再幫幫他嗎?
 

Input
第一行,一個整數N(1<=N<=1000),表示病毒特徵碼的個數。
接下來N行,每行表示一個病毒特徵碼,特徵碼字符串長度在1—50之間,並且只包含“英文大寫字符”。任意兩個病毒特徵碼,不會完全相同。
在這之後一行,表示“萬惡之源”網站源碼,源碼字符串長度在2000000之內。字符串中字符都是ASCII碼可見字符(不包括回車)。
 

Output
按以下格式每行一個,輸出每個病毒出現次數。未出現的病毒不需要輸出。
病毒特徵碼: 出現次數
冒號後有一個空格,按病毒特徵碼的輸入順序進行輸出。
 

Sample Input
3 AA BB CC ooxxCC%dAAAoen....END
 

Sample Output
AA: 2 CC: 1
Hint
Hit: 題目描述中沒有被提及的所有情況都應該進行考慮。比如兩個病毒特徵碼可能有相互包含或者有重疊的特徵碼段。 計數策略也可一定程度上從Sample中推測。
 
代碼:
#include <cstdio>
#include <queue>
#include <cstring>
#define KIND 26
#define SIZE 2000100
using namespace std ;
int d[1010] ;
char t[1010][55] , des[SIZE];
struct Trie{
	int index ;
	Trie* next[KIND] ;
	Trie *fail ;
	Trie()
	{
		for(int i = 0 ; i < KIND ; ++i)
			next[i] = NULL ;
		fail = NULL ;
		index = 0 ;
	}
}*root;

void insert(char str[] , int index)
{
	int len = strlen(str) ;
	Trie *t = root ;
	for(int i = 0 ; i < len ; ++i)
	{
		if(t->next[str[i]-'A'] == NULL)
		{
			t->next[str[i]-'A'] = new Trie() ;
		}
		t = t->next[str[i]-'A'] ;
	}
	t->index = index ;
}

void bfs()
{
	queue<Trie *> que ;
	que.push(root) ;
	while(!que.empty())
	{
		Trie *now = que.front() ;
		que.pop() ;
		for(int i = 0 ; i < KIND ; ++i)
		{
			if(now->next[i] != NULL)
			{
				if(now == root)
					now->next[i]->fail = root ;
				else
				{
					Trie *p = now->fail ;
					while(p)
					{
						if(p->next[i])
						{
							now->next[i]->fail = p->next[i] ;
							break ;
						}
						p = p->fail ;
					}
					if(!p)
						now->next[i]->fail = root ;
				}
				que.push(now->next[i]) ;
			}
		}
	}
}

void query(char str[])
{
	int len = strlen(str) , i = 0;
	Trie *now = root ;
	while(str[i])
	{
		if(str[i]<'A' || str[i]>'Z')
		{
			++i ;
			now = root ;
			continue ;
		}
		int pos = str[i]-'A' ;
		while(now->next[pos]==NULL && now != root)
			now = now->fail ;
		now = now->next[pos] ;
		if(now == NULL)
			now = root ;
		Trie * temp = now ;
		while( temp!=root )
		{
			d[temp->index] ++ ;
			temp = temp->fail ;
		}
		++i ;
	}
}

void del(Trie *t)
{
	for(int i = 0 ; i < KIND ; ++i)
	{
		if(t->next[i])
			del(t->next[i]) ;
	}
	delete t ;
}
int main()
{
	int n ;
	while(~scanf("%d",&n))
	{
		root = new Trie() ;
		getchar() ;
		for(int i = 1 ; i <= n ; ++i)
		{
			gets(t[i]) ;
			insert(t[i] , i) ;
			d[i] = 0 ;
		}
		gets(des) ;
		bfs() ;
		query(des) ;
		for(int i = 1 ; i <= n ; ++i )
		{
			if(d[i]>0)
				printf("%s: %d\n",t[i],d[i]) ;
		}
		del(root) ;
	}
	return 0 ;
}

與君共勉
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章