HDU 2896 病毒侵袭 AC自动机
//#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define pb(a) push_back(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r #define PI 3.1415926535898 template<class T> T min(const T& a,const T& b,const T& c) { return min(min(a,b),min(a,c)); } template<class T> T max(const T& a,const T& b,const T& c) { return max(max(a,b),max(a,c)); } void debug() { #ifdef ONLINE_JUDGE #else freopen("d:\\in.txt","r",stdin); // freopen("d:\\out1.txt","w",stdout); #endif } int getch() { int ch; while((ch=getchar())!=EOF) { if(ch!=' '&&ch!='\n')return ch; } return EOF; } const int SIGMA_SIZE=128; struct node { node *next[SIGMA_SIZE]; node *fail; int val; node(){memset(next,0,sizeof(next));fail=NULL;val=0;} }; struct ACAutomation { node* root; void init(){root=new node;} int insert(const char *s,const int& v) { node *p=root; for(int i=0;s[i]!='\0';i++) { if(p->next[s[i]]!=NULL)p=p->next[s[i]]; else p=p->next[s[i]]=new node; } p->val=v; return 0; } int construct() { root->fail=root; queue<node*> q; for(int c=0;c<SIGMA_SIZE;c++) { node *u=root->next[c]; if(u!=NULL){u->fail=root;q.push(u);} } while(!q.empty()) { node *r=q.front();q.pop(); for(int c=0;c<SIGMA_SIZE;c++) { node* u=r->next[c]; if(u==NULL){r->next[c]=r->fail->next[c];continue;} q.push(u); node* v=r->fail; while(v!=root&&v->next[c]!=NULL)v=v->fail; u->fail=v->next[c]; } } return 0; } void count(node *u,int &num,int *da) { if(u->val&&!da[u->val]) { num++; da[u->val]=1; } if(u->fail!=root&&!da[u->fail->val])count(u->fail,num,da); } int find(const char *s,int *da) { int num=0; node * u=root; for(int i=0;s[i]!='\0';i++) { u=u->next[s[i]]; if(u->val)count(u,num,da); } return num; } void free(node *p) { for(int c='a';c<SIGMA_SIZE;c++) if(p->next[c]!=NULL)free(p->next[c]); delete p; } }ac; int n,m; char T[10010]; int main() { while(scanf("%d",&n)!=EOF) { ac.init(); char s[222]; for(int i=1;i<=n;i++) { scanf("%s",s); ac.insert(s,i); } ac.construct(); scanf("%d",&m); int num=0; for(int i=1;i<=m;i++) { scanf("%s",T); int da[555]; memset(da,0,sizeof(da)); int k=ac.find(T,da); if(k>0) { printf("web %d:",i); for(int j=1;j<=500;j++)if(da[j]) printf(" %d",j); printf("\n"); num++; } } printf("total: %d\n",num); // ac.free(ac.root); } return 0; }