HDU 3065 AC自动机 模板题

题目链接

水题不多说 没关freopen WA了一次

代码如下:


#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <set>
#define sf scanf
#define pf printf
using namespace std;
const int sigma_size = 26;
typedef struct Trie_Node* poi_Node;
struct Trie_Node{
    int v;
    poi_Node next[sigma_size];
    poi_Node fail;
};
poi_Node root;
poi_Node make_node(){
    poi_Node cur = new Trie_Node;
    cur -> v = 0;
    memset(cur -> next,NULL,sizeof(cur -> next));
    cur -> fail = NULL;
    return cur;
}
void Insert(char* s,int v){
    int len = strlen(s);
    poi_Node cur = root;
    for(int i = 0;i < len;++i){
        int idx = s[i] - 'A';
        if(cur -> next[idx] == NULL){
            cur -> next[idx] = make_node();
        }
        cur = cur -> next[idx];
    }
    cur -> v = v;
}

void get_fail(){
    queue<poi_Node> q;
    q.push(root);
    while( !q.empty() ){
        poi_Node cur = q.front();q.pop();

        for(int i = 0;i < sigma_size;++i){
            if(cur -> next[i]){
                poi_Node p = cur -> fail;
                while(p && !p -> next[i]) p = p -> fail;
                cur -> next[i] -> fail = p ? p -> next[i] : root;
                q.push(cur -> next[i]);
            }
        }
    }
}

char str[2000000 + 5];
char bug[1005][55];
int cnt[1005];
void Search(char* s){
    int len = strlen(s);
    poi_Node cur = root;
    for(int i = 0;i < len;++i){
        int idx = s[i] - 'A';
        if(idx < 0 || idx >= 26){
            cur = root;
            continue;
        }
        if(cur -> next[idx] == NULL){
            while(cur && cur -> next[idx] == NULL) cur = cur -> fail;
            if(cur == NULL) cur = root;
            else cur = cur -> next[idx];
        }else cur = cur -> next[idx];

        poi_Node p = cur;
        while(p){
            if(p -> v > 0){
                cnt[p -> v] ++;
            }
            p = p -> fail;
        }
    }
}

void DFS(poi_Node ROOT){
    for(int i = 0; i < sigma_size;++i) if(ROOT -> next[i]) DFS(ROOT -> next[i]);
    ROOT -> v = 0;
}

int main(){
//    freopen("read.txt","r",stdin);
    int n;
    root = make_node();
    while( sf("%d",&n) != EOF ){
        memset(cnt,0,sizeof(cnt));
        for(int i = 0;i < n;++i){
            sf("%s",str);
            strcpy(bug[i + 1],str);
            Insert(str,i + 1);
        }
        get_fail();
        sf("%s",str);
        Search(str);
        for(int i = 1;i <= n;++i){
            if(cnt[i]){
                pf("%s: %d\n",bug[i],cnt[i]);
            }
        }
        DFS(root);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值