一般方法超时,后面用ac自动机做秒过,据说是数据太弱!!
#include<bits/stdc++.h>
using namespace std;
string str,st[10005],stt[10005];
int k,flag,j;
struct node
{
node *next[10],*fail;
int cnt,id;
void init()
{
for(int i=0;i<10;i++)
next[i]=NULL;
fail=NULL;
cnt=0;
}
}*root;
void mt(string s)
{
node *p=root;
for(int i=0;i<s.size();i++)
{
int pos=s[i]-'0';
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 *temp,*son,*p=root;
queue<node *>qu;
qu.push(p);
while(!qu.empty())
{
temp=qu.front();
qu.pop();
for(int i=0;i<10;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()
{
node *p=root,*temp;
j=0;
for(int i=0;i<str.size();i++)
{
int pos=str[i]-'0';
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>=0)
{
if(temp->cnt)
{
flag=1;
stt[j++]=st[temp->id];
}
temp->cnt=-1;
temp=temp->fail;
}
else
break;
}
}
}
int dt(node *T)
{
if(T==NULL)
return 0;
for(int i=0;i<10;i++)
if(T->next[i])
dt(T->next[i]);
free(T);
return 0;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
root=new node;
root->init();
string sg;
k=flag=0;
for(int i=0;i<n;i++)
{
cin>>sg;
str+=sg;
}
for(int i=0;i<m;i++)
{
string s1,s2,s3,s4;
cin>>s1>>s2>>s3>>s4;
st[i]=s1+" "+s2+" "+s3;
mt(s4);
}
mf();
sm();
if(flag)
{
cout<<"Found key:";
for(int i=0;i<j;i++)
cout<<" "<<stt[i];
cout<<"\n";
}
else
cout<<"No key can be found !\n";
dt(root);
}
return 0;
}