病毒侵襲持續中
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7685 Accepted Submission(s): 2687
接下來N行,每行表示一個病毒特徵碼,特徵碼字符串長度在1—50之間,並且只包含“英文大寫字符”。任意兩個病毒特徵碼,不會完全相同。
在這之後一行,表示“萬惡之源”網站源碼,源碼字符串長度在2000000之內。字符串中字符都是ASCII碼可見字符(不包括回車)。
病毒特徵碼: 出現次數
冒號後有一個空格,按病毒特徵碼的輸入順序進行輸出。
#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 ;
}
與君共勉