hdu 2222 Keywords Search(AC自动机)

Keywords Search

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18580    Accepted Submission(s): 6191


Problem Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.

Input
First line will contain one integer means how many cases will follow by.
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.

Output
Print how many keywords are contained in the description.

Sample Input
1 5 she he say shr her yasherhs

Sample Output
3

Author
Wiskey

Recommend

lcy

 

AC 自动机

#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
class node
{
  public:
  node*next[26];
  node*fail;
  int count;
  node()
  {
    memset(next,NULL,sizeof(next));
    fail=NULL;count=0;
  }
};
void insert(node*root,char s[])
{
  node*p=root;
  int i=0,num;
  while(s[i]!='\0')
  {
    num=s[i]-'a';
    if(p->next[num]==NULL)
    p->next[num]=new node;
    p=p->next[num];
    i++;
  }
  p->count++;
}
void AC(node*root)
{
  int i;
  queue<node*>Q;
  root->fail=NULL;
  Q.push(root);
  node *p,*temp;
  while(!Q.empty())
  {
    temp=Q.front();
    Q.pop();
    for(i=0;i<26;i++)
    {
      if(temp->next[i]!=NULL)
      {
        p=temp->fail;
        while(p!=NULL)
        {
          if(p->next[i]!=NULL)
          {
            temp->next[i]->fail=p->next[i];
            break;
          }p=p->fail;
        }
        if(p==NULL)
        {
          temp->next[i]->fail=root;
        }
        Q.push(temp->next[i]);
      }
    }
  }
}
int ques(node*root,char s[])
{
  int ans=0;
  int num;
  int i=0;node*p=root;
  while(s[i]!='\0')
  {
    num=s[i]-'a';
    while(p->next[num]==NULL&&p!=root)
    {
      p=p->fail;
    }
    p=p->next[num];
    if(p==NULL)
    p=root;
    node *temp=p;
    while(temp!=root&&temp->count!=-1)
    {
      ans+=temp->count;
      temp->count=-1;
      temp=temp->fail;
    }
    i++;
  }
 return ans;
}
int main()
{
  int t;
  cin>>t;
  char s[60];
  char f[1003000];
  while(t--)
  {
    int n;node*root=new node();
    cin>>n;
    for(int i=0;i<n;i++)
    {
      cin>>s;
      insert(root,s);
    }
    AC(root);
    cin>>f;
    int ans=ques(root,f);
    cout<<ans<<endl;
  }
}


 

posted @ 2012-08-02 12:41  剑不飞  阅读(105)  评论(0编辑  收藏  举报