/* ac自动机*/
#include<bits/stdc++.h>
using namespace std;
#define ms(x) memset(x,0,sizeof(x))
const int M =1e5+10;
namespace AC
{
int ch[M][26],de[M],f[M],vis[M],cnt=0,q[M*2];
inline void Init()
{
ms(vis);ms(f);ms(de);cnt=0;f[0]=-1;ms(ch);
}
void Insert(char *s)
{
int r=0;
for(int i=0;s[i];++ i)
{
if(!ch[r][s[i]-'a'])
{
++cnt;
ms(ch[cnt]);
ch[r][s[i]-'a'] = cnt;
de[cnt]=i+1;
}
r = ch[r][s[i]-'a'];
}
}
void Getfail()
{
int t=0,x;
for(int i=0;i<26;i++) if(ch[0][i]) q[++t]=ch[0][i];
for(x=1;x<=t;x++)
{
int xx=x;
x =q[xx];
for(int i=0;i<26;++ i)
if(ch[x][i]) f[ch[x][i]]=ch[f[x]][i],q[++t]=ch[x][i];
else ch[x][i] =ch[f[x]][i];
x =xx;
}
}
int Ans(char *s1,char *s2,int vi)
{
int ans=0;
for(int l=strlen(s1),i=0,x=0;i<l;i++)
{
while(!ch[x][s1[i]-'a']) x=f[x];
x =ch[x][s1[i]-'a'];
for(int j=x;j;j=f[j]) vis[j]=vi;
}
for(int l=strlen(s2),i=0,x=0;i<l;i++)
{
while(!ch[x][s2[i]-'a']) x=f[x];
x =ch[x][s2[i]-'a'];
for(int j=x;j;j=f[j]) if(vis[j]==vi) ans =max(ans,de[j]);
}
return ans;
}
};
char s[110][M];
//AC ac;
int main()
{
int t,n,m;
scanf("%d",&t);
while(t--)
{
using namespace AC;
Init();
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%s",s[i]);
Insert(s[i]);
}
Getfail();
scanf("%d",&m);
while(m--)
{
int x1,x2;
scanf("%d%d",&x1,&x2);
printf("%d\n",Ans(s[x1],s[x2],m+1));
}
}
return 0;
}
07-13
07-13
07-13
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交