hdoj 2222

时间:2023-03-09 17:55:10
hdoj 2222

http://acm.hdu.edu.cn/showproblem.php?pid=2222

第一道 AC自动机。。。。。trie树的建立 和 AC自动机的查询,,可作模版。。。

解题思路:AC的应用。。。直接模版。。

 #include <iostream>
#include<cstring>
using namespace std;
struct point {
struct point *final;
struct point *next[];
int count;
point(){
final =NULL;
count =;
memset(next,NULL,sizeof(next));
}
}*q[]; char str[];
char tt[];
int head, tail; void build_trie(char *str, point *root){
point *p = root;
int i=,index;
while(str[i]){
index = str[i]-'a';
if(p->next[index]==NULL) p->next[index] = new point();
p = p->next[index];
i++;
}
p->count++;
} void get_final(point *root){
int i;
root->final = NULL;
q[head++] = root;
while(head!=tail){
point *temp = q[tail++];
point *p = NULL;
for(i=;i<;i++){
if(temp->next[i]!=NULL){
if(temp==root) temp->next[i]->final=root;
else{
p = temp->final;
while(p!=NULL){
if(p->next[i]!=NULL){
temp->next[i]->final = p->next[i];
break;
}
p = p->final;
}
if(p==NULL) temp->next[i]->final=root;
}
q[head++] = temp->next[i];
}
}
}
} int requry(point *root){
int i =,cnt=,index;
//int len = strlen(t);
point *p =root;
while(tt[i]){
index = tt[i]-'a';
while(p->next[index]==NULL&&p!=root) p= p->final;
p = p->next[index];
p=(p==NULL)? root:p;
point *temp =p;
while(temp!=root&&temp->count!=-){
//cout<<"------------>"<<endl;
cnt += temp->count;
temp->count=-;
temp = temp->final;
}
i++;
} return cnt;
}
int main()
{
int t;
cin>>t;
while(t--){
int n;
head =tail =;
point *root = new point();
cin>>n;
while(n--){
cin>>str;
build_trie(str,root);
}
get_final(root);
cin>>tt; cout<<requry(root)<<endl;
}
return ;
}