HDU 5384 字典树、AC自动机

时间:2023-03-09 01:40:21
HDU 5384 字典树、AC自动机

题目:http://acm.hdu.edu.cn/showproblem.php?pid=5384

用字典树、AC自动机两种做法都可以做

 #include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
using namespace std;
struct node{
int cnt;
node *next[];
node(){
cnt = ;
for(int i = ;i<;i++)
next[i] = NULL;
}
}*a;
void insert(char *str){
node *head = a;
int len = strlen(str);
for(int i = ;i<len;i++){
int temp = str[i]-'a';
if(head->next[temp] == NULL)
head->next[temp] = new node;
head = head->next[temp];
}
head->cnt++;
}
int find(string t){
node *head = a;
int ans = ;
for(int i = ;i<t.size();i++){
if(head->next[t[i]-'a']){
if(head->next[t[i]-'a']->cnt){
ans++; }
}else
break;
head = head->next[t[i]-'a'];
}
head->cnt--;
return ans;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
a = new node;
int n;
scanf("%d",&n);
char s[];
for(int i = ;i<n;i++){
scanf(" %s",s);
insert(s);
}
string des;
cin >> des;
int ans = ;
for(int i = ;i<des.size();i++){
ans += find(des.substr(i));
}
printf("%d\n",ans);
}
return ;
}

字典树

 #include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
using namespace std;
struct node{
int cnt;
node *next[];
node(){
cnt = ;
for(int i = ;i<;i++)
next[i] = NULL;
}
}*a;
void insert(char *str){
node *head = a;
int len = strlen(str);
for(int i = ;i<len;i++){
int temp = str[i]-'a';
if(head->next[temp] == NULL)
head->next[temp] = new node;
head = head->next[temp];
}
head->cnt++;
}
int find(string t){
node *head = a;
int ans = ;
for(int i = ;i<t.size();i++){
if(head->next[t[i]-'a']){
if(head->next[t[i]-'a']->cnt){
ans++; }
}else
break;
head = head->next[t[i]-'a'];
}
head->cnt--;
return ans;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
a = new node;
int n;
scanf("%d",&n);
char s[];
for(int i = ;i<n;i++){
scanf(" %s",s);
insert(s);
}
string des;
cin >> des;
int ans = ;
for(int i = ;i<des.size();i++){
ans += find(des.substr(i));
}
printf("%d\n",ans);
}
return ;
}

AC自动机