题目链接:Click here~~
题意:
有 n 个 key words ,然后给一个主串,询问主串中最多能匹配出多少种 key words。(每种只统计一次)
解题思路:
由于括号中的条件,可以将每个节点加一个 vis 标记是否已经访问过此节点。
这样可以在循环时候加一个剪枝,如果下个节点已经访问过,不必再访问。
#include <queue>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define CLR(a,v) memset(a,v,sizeof(a))
namespace Trie
{
const int N = 1e6 + 5;
const int Size = 26;
int top;
struct Node{
Node *next[Size], *f;
int ended_cnt;
bool vis;
}node[N], *root;
inline Node* new_node()
{
node[top].vis = false;
node[top].ended_cnt = 0;
CLR(node[top].next,false);
return &node[top++];
}
void init()
{
top = 0;
root = new_node();
}
void insert(char *s)
{
Node *u = root;
for(int i=0;s[i];i++)
{
int id = s[i] - 'a';
if(u->next[id] == NULL)
u->next[id] = new_node();
u = u->next[id];
}
u->ended_cnt++;
}
}
namespace ACam
{
using namespace Trie;
void get_fail()
{
queue<Node*> Q;
for(int i=0;i<Size;i++)
{
Node *&ch = root->next[i];
if(!ch)
ch = root;
else
{
ch->f = root;
Q.push(ch);
}
}
while(!Q.empty())
{
Node *cur = Q.front();Q.pop();
for(int i=0;i<Size;i++)
{
Node *&ch = cur->next[i];
if(!ch)
ch = cur->f->next[i];
else
{
ch->f = cur->f->next[i];
Q.push(ch);
}
}
}
}
int match(char *s)
{
int ans = 0;
Node *u = root;
for(int i=0;s[i];i++)
{
int id = s[i] - 'a';
u = u->next[id];
Node *v = u;
while(v != root && !v->vis)
{
v->vis = true;
ans += v->ended_cnt;
v = v->f;
}
}
return ans;
}
}
const int N = 1e6 + 5;
char str[N];
int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
ACam::init();
scanf("%d",&n);
while(n--)
{
scanf("%s",str);
ACam::insert(str);
}
ACam::get_fail();
scanf("%s",str);
printf("%d\n",ACam::match(str));
}
return 0;
}