记录一个菜逼的成长。。
题目链接
题目大意:
给你n个只包含大写字母的字符串,最后一行给你一个字符串,问这个字符串分别包含每种字符串多少个。
要统计数量,而不是种数。
#include <bits/stdc++.h>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
typedef long long LL;
const int INF = 0x3f3f3f3f;
int c[1010];
struct Trie
{
int next[50010][128],fail[50010],cnt[50010],num[50010];
int root,L,id;
int newnode()
{
for(int i = 0;i < 128;i++)
next[L][i] = -1;
cnt[L++] = 0;num[L-1] = 0;
return L-1;
}
void init()
{
L = 0;id = 1;
root = newnode();
}
void Insert(char buf[])
{
int len = strlen(buf);
int now = root;
for(int i = 0;i < len;i++)
{
if(next[now][buf[i]] == -1)
next[now][buf[i]] = newnode();
now = next[now][buf[i]];
}
cnt[now]++;num[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]);
}
}
}
int query(char buf[])
{
int len = strlen(buf);
int now = root;
int res = 0;
for(int i = 0;i < len;i++)
{
now = next[now][buf[i]];
int temp = now;
while( temp != root )
{
if(cnt[temp]){
c[num[temp]] += cnt[temp];
}
res += cnt[temp];
//cnt[temp] = 0;
temp = fail[temp];
}
}
}
};
const int maxn = 2000000 + 10;
char str[maxn],s[1010][55];
Trie ac;
int main()
{
int n;
while(~scanf("%d",&n)){
ac.init();
cl(c,0);
for( int i = 1; i <= n; i++ ){
scanf("%s",s[i]);
ac.Insert(s[i]);
}
ac.build();
scanf("%s",str);
ac.query(str);
for( int i = 1; i <= n; i++ ){
if(c[i])printf("%s: %d\n",s[i],c[i]);
}
}
return 0;
}