3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
AC自动机,这次1Y。
#include <stdio.h> #include <string.h> #include <queue> #include <algorithm> using namespace std; typedef struct { int fail,word; int next[100]; }Tree; Tree tree[1000005]; char str[10005]; queue <int> q; int ans[10]; int up,num; bool cmp(int x,int y) { return x<y; } void Add(char *str,int t) { int i,j,now,n; now=0; n=strlen(str); for (i=0;i<n;i++) { if (tree[now].next[str[i]-30]==-1) { tree[now].next[str[i]-30]=up; tree[up].word=-1; memset(tree[up].next,-1,sizeof(tree[up].next)); up++; } now=tree[now].next[str[i]-30]; } tree[now].word=t; } void BFS() { int i,j,tag,t,p; q.push(0); while(!q.empty()) { tag=q.front(); q.pop(); for (i=0;i<100;i++) { if (tree[tag].next[i]==-1) continue; t=tree[tag].next[i]; q.push(t); if (tag==0) { tree[t].fail=0; continue; } p=tree[tag].fail; while(tree[p].next[i]==-1 && p!=0) { p=tree[p].fail; } if (tree[p].next[i]!=-1) { tree[t].fail=tree[p].next[i]; } else { tree[t].fail=0; } } } } void Count(char *str) { int i,j,n,now,tag; n=strlen(str); now=0; for (i=0;i<n;i++) { while(tree[now].next[str[i]-30]==-1 && now!=0) { now=tree[now].fail; } if (tree[now].next[str[i]-30]!=-1) { now=tree[now].next[str[i]-30]; } tag=now; while(tag!=0) { if (tree[tag].word!=-1) { ans[num++]=tree[tag].word; } tag=tree[tag].fail; } } } int main() { int i,j,n,m,cnt; while(scanf("%d",&n)!=EOF) { up=1; memset(tree[0].next,-1,sizeof(tree[0].next)); for (i=0;i<n;i++) { scanf("%s",str); Add(str,i); } BFS(); scanf("%d",&m); cnt=0; for (i=0;i<m;i++) { getchar(); gets(str); num=0; Count(str); if (num==0) continue; sort(ans,ans+num,cmp); printf("web %d: ",i+1); for (j=0;j<num-1;j++) { printf("%d ",ans[j]+1); } printf("%d\n",ans[j]+1); cnt++; } printf("total: %d\n",cnt); } return 0; }