HDU 3065 AC自动机模版题

146 篇文章 0 订阅
9 篇文章 0 订阅

点击打开链接

题意:中文题不解释了

思路:用AC自动机,套模版而已,注意记录就行,纯套模版,真心没什么好说的

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=5000010;
const int N=26;
struct node{
    node *fail;
    node *next[N];
    int num;
    node(){
        fail=NULL;
        num=0;
        memset(next,NULL,sizeof(next));
    }
}*q[maxn];
char str1[1010][52];
char str2[2000010];
bool vis[1010];
int head,tail,ans[1010];
void insert_Trie(char *str,node *root,int cn){
    node *p=root;
    int i=0;
    while(str[i]){
        int id=str[i]-'A';
        if(p->next[id]==NULL) p->next[id]=new node();
        p=p->next[id];i++;
    }
    p->num=cn;
}
void build_ac(node *root){
    root->fail=NULL;
    q[head++]=root;
    while(head!=tail){
        node *temp=q[tail++];
        node *p=NULL;
        for(int i=0;i<N;i++){
            if(temp->next[i]!=NULL){
                if(temp==root) temp->next[i]->fail=root;
                else{
                    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[head++]=temp->next[i];
            }
        }
    }
}
void query(node *root){
    int i=0;
    node *p=root;
    while(str2[i]){
        if(str2[i]<'A'||str2[i]>'Z'){
            i++;
            p=root;continue;
        }
        int id=str2[i]-'A';
        while(p->next[id]==NULL&&p!=root) p=p->fail;
        p=p->next[id];
        p=(p==NULL)?root:p;
        node *temp=p;
        while(temp!=root){
            vis[temp->num]=1;
            if(temp->num!=0) ans[temp->num]++;
            temp=temp->fail;
        }
        i++;
    }
}
int main(){
    int n,m;
    while(scanf("%d",&n)!=-1){
        getchar();
        memset(vis,0,sizeof(vis));
        memset(ans,0,sizeof(ans));
        node *root=new node();
        head=tail=0;
        for(int i=1;i<=n;i++){
            gets(str1[i]);
            insert_Trie(str1[i],root,i);
        }
        build_ac(root);
        gets(str2);
        query(root);
        for(int i=1;i<=n;i++){
            if(vis[i]){
                int len=strlen(str1[i]);
                for(int j=0;j<len;j++) printf("%c",str1[i][j]);
                printf(": %d\n",ans[i]);
            }
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值