题目:输出出现次数最多的单词(有几个输出几个,而且按之前给的顺序输出),之前被题目误解了,以为只要重复出现就要输出!!还有就是题目说单词数量最多是150,结果我开到200才给过!!因此wrong了好多次!!!以后数组尽量开大些!
解法:ac自动机模板题+map(单词可能会出现多次,这里要处理一下)!
#include<bits/stdc++.h>
using namespace std;
char str1[1000100],str[255][105],str2[255][105];
int a[255],n,k;
struct node
{
int cnt,id;
node *next[26],*fail;
void init()
{
for(int i=0;i<26;i++)
next[i]=NULL;
cnt=0;
fail=NULL;
}
}*root;
void mt(char *s)
{
node *p=root;
int len=strlen(s);
for(int i=0;i<len;i++)
{
int pos=s[i]-'a';
if(p->next[pos]==NULL)
{
p->next[pos]=new node;
p->next[pos]->init();
p=p->next[pos];
}
else
p=p->next[pos];
}
p->cnt++;
p->id=++k;
}
void mf()
{
node *son,*temp,*p=root;
queue<node *>qu;
qu.push(p);
while(!qu.empty())
{
temp=qu.front();
qu.pop();
for(int i=0;i<26;i++)
{
son=temp->next[i];
if(son)
{
if(temp==root)
son->fail=root;
else
{
p=temp->fail;
while(p)
{
if(p->next[i])
{
son->fail=p->next[i];
break;
}
p=p->fail;
}
if(!p)
son->fail=root;
}
qu.push(son);
}
}
}
}
void sm()
{
int len=strlen(str1);
node *p=root,*temp;
for(int i=0;i<len;i++)
{
int pos=str1[i]-'a';
while(!p->next[pos]&&p!=root)
p=p->fail;
p=p->next[pos];
if(!p)
p=root;
temp=p;
while(temp!=root)
{
if(temp->cnt)
a[temp->id]++;
temp=temp->fail;
}
}
}
int dt(node* T)
{
if(T==NULL)
return 0;
for(int i=0;i<26;i++)
if(T->next[i])
dt(T->next[i]);
free(T);
return 0;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
k=0;
map<string,int>pq;
memset(a,0,sizeof(a));
root=new node;
root->init();
int v=1;
for(int i=1;i<=n;i++)
{
scanf("%s",str[i]);
if(!pq.count(str[i]))
{
mt(str[i]);
pq[str[i]]=-1;
strcpy(str2[v++],str[i]);
}
}
mf();
scanf("%s",str1);
sm();
int maxn=-1;
for(int i=1;i<=k;i++)
if(a[i]>maxn)
maxn=a[i];
printf("%d\n",maxn);
for(int i=1;i<=k;i++)
if(a[i]==maxn)
pq[str2[i]]=maxn;
for(int i=1;i<=n;i++)
if(pq[str[i]]==maxn)
printf("%s\n",str[i]);
dt(root);
}
return 0;
}