题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2896
题意:这是中文题目,也没有什么会产生多重语义的地方,不说了
思路:既然题目都要求匹配个数了,就直接上AC自动机吧,此题在于要保存一下字符串的顺序,在建立Trie树时,在最后一个节点上加上个id就可以了,询问时再输出出来
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 210*500;
struct Trie
{
int next[maxn][128], fail[maxn], last[maxn];
int root, L;
int newnode()
{
for(int i = 0; i < 128; ++i) next[L][i] = -1;
last[L++] = -1;
return L-1;
}
void init()
{
L = 0;
root = newnode();
}
void insert(char s[], int id)
{
int len = strlen(s), now = root;
for(int i = 0; i < len; ++i){
if(next[now][s[i]] == -1)
next[now][s[i]] = newnode();
now = next[now][s[i]];
}
last[now] = id;
}
void build()
{
queue<int> Q;
fail[root] = root;
for(int i = 0; i < 128; ++i){
if(next[root][i] == -1) next[root][i] = root;
else{
fail[next[root][i]] = root;
Q.push(next[root][i]);
}
}
while(!Q.empty()){
int now = Q.front();
Q.pop();
for(int i = 0; i < 128; ++i){
if(next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else{
fail[next[now][i]] = next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
}
bool used[505];
bool query(char web[], int n, int id)
{
int len = strlen(web), now = root;
memset(used, false, sizeof(used));
bool flag = false;
for(int i = 0; i < len; ++i){
now = next[now][web[i]];
int temp = now;
while(temp != root){
if(last[temp] != -1){
used[last[temp]] = true;
flag = true;
}
temp = fail[temp];
}
}
if(!flag) return false;
printf("web %d:", id);
for(int i = 1; i <= n; ++i){
if(used[i]) printf(" %d", i);
}
cout << '\n';
return true;
}
};
char web[10005];
Trie trie;
int main()
{
int n, m;
scanf("%d", &n);
trie.init();
for(int i = 1; i <= n; ++i){
scanf("%s", web);
trie.insert(web, i);
}
trie.build();
int ans = 0;
scanf("%d", &m);
for(int i = 1; i <= m; ++i){
scanf("%s", web);
if(trie.query(web, n, i)) ans++;
}
printf("total: %d\n", ans);
return 0;
}