【hdu 2222】Keywords Search

Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 48720 Accepted Submission(s): 15551

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

AC-auto

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
#define maxn 1000005
using namespace std;
int T,n;
char aa[55],s[maxn];
int ans;
struct node{
    int ch[27],nex,cnt;
    void init()
    {
        nex=0;
        cnt=0;
        for(int i=0;i<=27;i++) ch[i]=0;
    }
}t[10005*51];
int tot;
queue<int> q;
inline void insert(char s[])
{
    int l=strlen(s);
    int now=0;
    for(int i=0;i<l;i++)
    {
        int tmp=s[i]-'a';
        if(!t[now].ch[tmp]) 
        {
            t[now].ch[tmp]=++tot; 
            t[tot].init();    
        }
        now=t[now].ch[tmp]; 
    }
    t[now].cnt++;
}
inline void get_nex()
{
    for(int i=0;i<27;i++)
    if(t[0].ch[i]) q.push(t[0].ch[i]); 
    while(!q.empty())
    {
        int now=q.front();
        q.pop();
        for(int i=0;i<26;i++)
        if(t[now].ch[i])
        {
                int tmp=t[now].nex;
                t[t[now].ch[i]].nex=t[tmp].ch[i];
                q.push(t[now].ch[i]);
        } 
        else t[now].ch[i]=t[t[now].nex].ch[i];
    }
} 
inline void solve()
{
    int i=0;
    int j=0;
    while(s[i])
    {
        int tt=s[i]-'a';
        while(j&&t[j].ch[tt]==0) j=t[j].nex;
        j=t[j].ch[tt];
        if(!j) {i++;continue;}
        int now=j;
        while(t[now].cnt!=-1&&now)
        {
            ans+=t[now].cnt;
            t[now].cnt=-1;
            now=t[now].nex;
        }
        i++;
    } 
}
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        t[0].init();
        tot=0;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%s",aa);
            insert(aa);
        }
        scanf("%s",s);
        get_nex();
        ans=0;
        solve();
        printf("%d\n",ans);
    }
}

你可能感兴趣的:(ac)