HDU2222 Keywords Search
题面:
- In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.
解题过程:
第一次写AC自动机,通过视频和博客学习理解了AC自动机原理以及大致的编程
- 参考视频:算法讲堂】【电子科技大学】【ACM】字符串算法选讲
- 参考博客:hdu2222
AC代码:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
#define rep(i,l,p) for(int i=l;i<=p;i++)
#define fread() freopen("in.txt","r",stdin)
#define mp make_pair
#define Fi first
#define Se second
#define endl '\n'
typedef long long ll;
int T,n;
const int N = 1e4+10, L = 1e6+10;
char s[L];
int num;
struct Node
{
int son[30];
int fail,cnt;
}a[N*60];
queue<int> q;
void clear(int x){
a[x].cnt = 0;
a[x].fail = 0;
memset(a[x].son,0,sizeof a[x].son);
}
void trie(char* c){
int l = strlen(c);
int x = 0;
for(int i=0;i<l;i++){
int t = c[i]-'a'+1;
if(!a[x].son[t]){
num++;
clear(num);
a[x].son[t] = num;
}
x = a[x].son[t];
}
a[x].cnt++;
}
void buildAC(){
while(!q.empty()) q.pop();
for(int i=1;i<=26;i++){
if(a[0].son[i]) q.push(a[0].son[i]);
}
while(!q.empty()){
int x = q.front();
q.pop();
int fail = a[x].fail;
for(int i=1;i<=26;i++){
int y = a[x].son[i];
if(y){
a[y].fail = a[fail].son[i];
q.push(y);
}else{
a[x].son[i] = a[fail].son[i];
}
}
}
return;
}
int find(char *c){
int l = strlen(c);
int x = 0,ans = 0;
for(int i=0;i<l;i++){
int t = c[i]-'a'+1;
while(x && !a[x].son[t]) x = a[x].fail;
x = a[x].son[t];
int p = x;
while(p && a[p].cnt != -1){
ans += a[p].cnt;
a[p].cnt = -1;
p = a[p].fail;
}
}
return ans;
}
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
int T;
cin >> T;
while(T--){
int n;
cin >> n;
num = 0;
clear(0);
for(int i=1;i<=n;i++){
cin >> s;
trie(s);
}
buildAC();
cin >> s;
cout << find(s) << endl;
}
return 0;
}