hdu2896 输出可以匹配串的id(AC自动机)
end数组表示id,开一个used数组记录哪些被匹配过
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 int used[505]; 7 struct AC 8 { 9 int next[500*205][128],fail[500*205],end[500*205]; 10 int root,L; 11 int newnode() 12 { 13 for (int i=0;i<128;i++) 14 next[L][i]=-1; 15 end[L++]=-1; 16 return L-1; 17 } 18 void init() 19 { 20 L=0; 21 root=newnode(); 22 } 23 void insert(char s[],int id) 24 { 25 int len=strlen(s),now=root; 26 for (int i=0;i<len;i++) 27 { 28 if (next[now][s[i]]==-1) 29 next[now][s[i]]=newnode(); 30 now=next[now][s[i]]; 31 } 32 end[now]=id; 33 } 34 void build() 35 { 36 queue<int>q; 37 fail[root]=root; 38 for (int i=0;i<128;i++) 39 if (next[root][i]==-1) 40 next[root][i]=root; 41 else{ 42 fail[next[root][i]]=root; 43 q.push(next[root][i]); 44 } 45 while (!q.empty()) 46 { 47 int now=q.front(); 48 q.pop(); 49 for (int i=0;i<128;i++) 50 if (next[now][i]==-1) 51 next[now][i]=next[fail[now]][i]; 52 else{ 53 fail[next[now][i]]=next[fail[now]][i]; 54 q.push(next[now][i]); 55 } 56 } 57 } 58 int query(char buf[]) 59 { 60 int len=strlen(buf),now=root; 61 int flag=0,temp; 62 for (int i=0;i<len;i++) 63 { 64 now=next[now][buf[i]]; 65 temp=now; 66 while (temp!=root) 67 { 68 if (end[temp]!=-1) 69 { 70 used[end[temp]]=1; 71 flag=1; 72 } 73 temp=fail[temp]; 74 } 75 } 76 return flag; 77 } 78 }; 79 AC ac; 80 char buf[10005]; 81 int main() 82 { 83 int i,ans,n,m,j; 84 while (~scanf("%d",&n)) 85 { 86 ac.init(); 87 for (i=1;i<=n;i++) 88 { 89 scanf("%s",buf); 90 ac.insert(buf,i); 91 } 92 ac.build(); 93 scanf("%d",&m); 94 ans=0; 95 for (i=1;i<=m;i++) 96 { 97 scanf("%s",buf); 98 memset(used,0,sizeof(used)); 99 if (ac.query(buf)) 100 { 101 ans++; 102 printf("web %d:",i); 103 for (j=1;j<=n;j++) 104 if (used[j]) printf(" %d",j); 105 printf("\n"); 106 } 107 } 108 printf("total: %d\n",ans); 109 } 110 return 0; 111 }