您的位置:首页 > 理论基础 > 数据结构算法

HDU 3065 AC自动机模版题

2016-03-29 20:38 405 查看
点击打开链接

题意:中文题不解释了

思路:用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
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息