题意:
T 组数据, N 个母串 ,M 个子串,求每个母串的匹配
思路:
子串可能相同,算多次匹配
代码:
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
struct Trie
{
int next[100010][26],fail[100010],end[100010];
int root,L;
int newnode()
{
for(int i = 0; i < 26; i++)
next[L][i] = -1;
end[L++] = 0;
return L-1;
}
void init()
{
L = 0;
root = newnode();
}
void insert(string buf)
{
int len = buf.size();
int now = root;
for(int i = 0; i < len; i++)
{
if(next[now][buf[i]-'a'] == -1)
next[now][buf[i]-'a'] = newnode();
now = next[now][buf[i]-'a'];
}
end[now]++;
}
void build()
{
queue<int>Q;
fail[root] = root;
for(int i = 0; i < 26; 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 < 26; 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]);
}
}
}
int query(string buf)
{
int len = buf.size();
int now = root;
int ans=0;
for(int i = 0; i < len; i++)
{
now = next[now][buf[i]-'a'];
int temp = now;
while( temp != root )
{
if(end[temp] != -1)
ans += end[temp];
temp = fail[temp];
}
}
return ans;
}
};
string buf[100100];
Trie ac;
int main()
{
ios::sync_with_stdio(false);
int n,m,T;
cin>>T;
while(T--){
cin>>n>>m;
for(int i = 0;i < n;i++)
cin>>buf[i];
ac.init();
for(int i = 0;i < m;i++){
string str;
cin>>str;
ac.insert(str);
}
ac.build();
for(int i = 0;i < n;i++)
cout<<ac.query(buf[i])<<endl;
}
return 0;
}