| Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
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.
Input
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.
Output
Sample Input
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
Source
简单的AC自动机(待解决)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 500010;
char str[1000010];
struct ACAutomaton{
int ch[maxn][26],fail[maxn],val[maxn],last[maxn],sz,root;
int newnode(){
memset(ch[sz],0,sizeof(ch[sz]));
val[sz] = 0;
return sz++;
}
void init(){
sz = 0;
root = newnode();
}
void insert(char *str){
int len = strlen(str);
int now = root;
for(int i = 0;i < len;i++){
int &tmp = ch[now][str[i]-'a'];
if(!tmp) tmp = newnode();
now = tmp;
}
val[now]++;
}
void getfail(){
queue<int> q;
fail[root] = root;
for(int i = 0;i < 26;i++){
int u = ch[root][i];
if(u){
fail[u] = last[u] = 0;
q.push(u);
}
}
while(!q.empty()){
int now = q.front();q.pop();
for(int i = 0;i < 26;i++){
int u = ch[now][i];
if(!u) ch[now][i] = ch[fail[now]][i];
else{
fail[u] = ch[fail[now]][i];
last[u] = val[fail[u]] ? fail[u]:last[fail[u]];
q.push(u);
}
}
}
}
int query(char *str){
int len = strlen(str);
int now = root;
int ret = 0;
for(int i = 0;i < len;i++){
now = ch[now][str[i]-'a'];
int tmp = now;
while(tmp != root && val[tmp]){
ret += val[tmp];
val[tmp] = 0;
tmp = last[tmp];
}
}
return ret;
}
}ac;
int main(){
int kase,n;
scanf("%d",&kase);
while(kase--){
ac.init();
scanf("%d",&n);
for(int i = 0;i < n;i++){
scanf("%s",str);
ac.insert(str);
}
ac.getfail();
scanf("%s",str);
printf("%d\n",ac.query(str));
}
return 0;
}
关键词搜索与匹配算法实现
本文探讨了如何通过关键词搜索算法实现图像检索系统的关键词匹配功能。详细解释了输入格式、输出要求以及具体实现过程,包括使用AC自动机进行关键词匹配,并提供了示例输入输出解析。
1117

被折叠的 条评论
为什么被折叠?



