Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18206 Accepted Submission(s):
4541
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 #include<algorithm> 6 #include<cmath> 7 using namespace std; 8 typedef long long LL; 9 const int maxn=100010; 10 char buf[maxn]; 11 int N,M,cnttot; 12 int ans[maxn],cntweb; 13 struct Tire{ 14 int next[maxn][130],end[maxn]; 15 vector<int> kin[maxn]; 16 int fail[maxn],root,tot; 17 int newnode(){ 18 for(int i=0;i<128;i++) next[tot][i]=-1; 19 end[tot++]=0; 20 return tot-1; 21 } 22 void init(){ 23 tot=0; 24 root=newnode(); 25 } 26 void insert(char buf[],int k){//把第 k种类型的病毒信息放在字典树中 27 int len=strlen(buf); 28 int now=root; 29 for(int i=0;i<len;i++){ 30 if(next[now][buf[i]]==-1) next[now][buf[i]]=newnode(); 31 now=next[now][buf[i]]; 32 } 33 end[now]++; kin[now].push_back(k); 34 } 35 void build(){ 36 queue<int> Q; 37 fail[root]=root; 38 for(int i=0;i<128;i++){ 39 if(next[root][i]==-1) next[root][i]=root; 40 else{ 41 fail[next[root][i]]=root; 42 Q.push(next[root][i]); 43 } 44 } 45 while(!Q.empty()){ 46 int now=Q.front(); Q.pop(); 47 for(int i=0;i<128;i++){ 48 if(next[now][i]==-1) next[now][i]=next[fail[now]][i]; 49 else{ 50 fail[next[now][i]]=next[fail[now]][i]; 51 Q.push(next[now][i]); 52 } 53 } 54 } 55 } 56 bool used[maxn]; 57 void query(char buf[],int num){ 58 int len=strlen(buf),now=root; 59 memset(used,false,sizeof(used)); 60 for(int i=0;i<len;i++){ 61 now=next[now][buf[i]]; 62 int tmp=now; 63 while(tmp!=root){ 64 if(end[tmp]!=0){ 65 for(int j=0;j<kin[tmp].size();j++){ 66 int y=kin[tmp][j]; 67 if(used[y]==false){ 68 ans[++cntweb]=y; 69 used[y]=true; 70 } 71 } 72 } 73 tmp=fail[tmp]; 74 } 75 } 76 if(cntweb!=0){ 77 cnttot++; 78 sort(ans+1,ans+cntweb+1); 79 printf("web %d:",num); 80 for(int i=1;i<=cntweb;i++) printf(" %d",ans[i]); 81 printf("\n"); 82 memset(ans,0,sizeof(ans)); cntweb=0; 83 } 84 } 85 }ac; 86 int main(){ 87 scanf("%d",&N); 88 ac.init(); 89 for(int i=1;i<=N;i++){ 90 scanf("%s",buf); 91 ac.insert(buf,i); 92 } 93 ac.build(); 94 scanf("%d",&M); 95 for(int i=1;i<=M;i++){ 96 scanf("%s",buf); 97 ac.query(buf,i); 98 } 99 printf("total: %d\n",cnttot); 100 return 0; 101 }
原文:http://www.cnblogs.com/CXCXCXC/p/5171285.html