您的位置:首页 > 其它

17ACM Qingdao 1003 The Dominator of Strings

2017-09-20 23:37 405 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=6208

分析:选任意一个最长的字符串,用KMP判断另外的串是否都在这个串内。

代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int Tmax=100005;
int n,p[Tmax],f[Tmax],maxlen,maxn,alen;
char s[Tmax],tmp[Tmax],a[Tmax],MT[Tmax];
bool ok;
void getfail()
{
int i=0,j=-1;
f[0]=-1;
alen=strlen(a);
while(i<alen)
{
if(j==-1||a[i]==a[j])
{
i++;
j++;
f[i]=j;
}
else j=f[j];
}
return;
}
bool KMP()
{
int i=0,j=0;
while(i<maxlen)
{
if(j==-1||MT[i]==a[j])
{
i++;
j++;
}
else j=f[j];
if(j==alen) return true;
}
return false;
}
int main()
{
int T,i,j,len;
scanf("%d",&T);
while(T--)
{
p[1]=1;
scanf("%d",&n);
maxlen=0;
ok=true;
for(i=1;i<=n;i++)
{
scanf("%s",tmp);
len=strlen(tmp);
if(len>maxlen)
{
maxlen=len;
maxn=i;
}
for(j=0;j<len;j++)
s[p[i]+j]=tmp[j];
p[i+1]=p[i]+len;
}
for(i=0;i<maxlen;i++)
MT[i]=s[p[maxn]+i];
MT[i]='\0';
for(i=1;i<=n;i++)
{
if(i==maxn) continue;
len=p[i+1]-p[i];
for(j=0;j<len;j++)
a[j]=s[p[i]+j];
a[j]='\0';
getfail();
if(KMP()==false){
printf("No\n");
ok=false;
break;
}
}
if(ok==true) printf("%s\n",MT);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: