HDU2222 Keywords Search AC自动机模板


题面:

  • 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.

解题过程:


AC代码:

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
#define rep(i,l,p) for(int i=l;i<=p;i++)
#define fread() freopen("in.txt","r",stdin)
#define mp make_pair
#define Fi first
#define Se second
#define endl '\n'
typedef long long ll;
int T,n;
const int N = 1e4+10, L = 1e6+10;
char s[L];
int num;
struct Node
{
    int son[30];
    int fail,cnt;
}a[N*60];
queue<int> q;
void clear(int x){
    a[x].cnt = 0;
    a[x].fail = 0;
    memset(a[x].son,0,sizeof a[x].son);
}
void trie(char* c){
    int l = strlen(c);
    int x = 0;
    for(int i=0;i<l;i++){
        int t = c[i]-'a'+1;
        if(!a[x].son[t]){
            num++;
            clear(num);
            a[x].son[t] = num;
        }
        x = a[x].son[t];
    }
    a[x].cnt++;
}
void buildAC(){
    while(!q.empty()) q.pop();
    for(int i=1;i<=26;i++){
        if(a[0].son[i]) q.push(a[0].son[i]);
    }
    while(!q.empty()){
        int x = q.front();
        q.pop();
        int fail = a[x].fail;
        for(int i=1;i<=26;i++){
            int y = a[x].son[i];
            if(y){
                a[y].fail = a[fail].son[i];
                q.push(y);
            }else{
                a[x].son[i] = a[fail].son[i];
            }
        }
    }
    return;
}
int find(char *c){
    int l = strlen(c);
    int x = 0,ans = 0;
    for(int i=0;i<l;i++){
        int t = c[i]-'a'+1;
        while(x && !a[x].son[t]) x = a[x].fail;
        x = a[x].son[t];
        int p = x;
        while(p && a[p].cnt != -1){
            ans += a[p].cnt;
            a[p].cnt = -1;
            p = a[p].fail;
        }
    }
    return ans;
}
int main(int argc, char const *argv[])
{
    ios::sync_with_stdio(false);
    int T;
    cin >> T;
    while(T--){
        int n;
        cin >> n;
        num = 0;
        clear(0);
        for(int i=1;i<=n;i++){
            cin >> s;
            trie(s);
        }
        buildAC();
        cin >> s;
        cout << find(s) << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值