把模板写上,改一下,改的方法我觉得需要积累
然后是从第一个串中枚举子串,判断
二分找出最长的
然后等长再判断字典序
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
char s[15][100];
char P[100];
char ans[100];//最终的结果字符串
int m,next[100];
int n;//表示有多少个主串
void getFail()
{
m=strlen(P);
next[0]=next[1]=0;
for(int i=1; i<m; i++)
{
int j =next[i];
while(j && P[i]!=P[j]) j=next[j];
next[i+1] = (P[i]==P[j])?j+1:0;
}
}
bool find(char *T)
{
int j=0;
getFail();
for(int i=0; i<60; i++)
{
while(j && T[i]!=P[j]) j=next[j];
if(T[i]==P[j]) j++;
if(j==m) return true;
}
return false;
}//模板;
bool solve_1(int len)//判断第0个base串的长为len的字串中是否有可行串
{
for(int i=0; i+len-1<60; i++)
{
strncpy(P,s[0]+i,len);
//char *strncpy(char *dest, const char *src, int n),
//把src所指向的字符串中以src地址开始
//的前n个字节复制到dest所指的数组中,并返回被复制后的dest。
P[len]=0;//P串末尾加'\0'//
bool ok=true;
for(int j=1; j<n; j++)
if(!find(s[j]))
{
ok=false;
break;
}
if(ok) return true;
}
return false;
}
void solve_3(int len)//找出长度为len的可行字串中字典序最小的,放在ans中
{
bool first=true;
for(int i=0; i+len-1<60; i++)
{
strncpy(P,s[0]+i,len);
P[len]=0;//P串末尾加'\0'
bool ok=true;
for(int j=1; j<n; j++)if(!find(s[j]))
{
ok=false;
break;
}
if(ok)
{
if(first)
{
strncpy(ans,P,len+1);
first=false;
}
else if(strcmp(ans,P)>0)//字典序小才更新
strncpy(ans,P,len+1);
}
}
}
bool solve()
{
int L=3,R=60;
if(!solve_1(3)) return false;
while(R>L)
{
int m=L+(R-L+1)/2;
if(solve_1(m))
L=m;
else
R=m-1;
}
//找到了可行字串的最长长度为L,然后需要找出字典序最小的
solve_3(L);//找到长L的字典序最小的字串存在ans中
return true;
}
int main()
{
int kase;
scanf("%d",&kase);
while(kase--)
{
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%s",s[i]);
if(!solve())//最终结果存在ans中
printf("no significant commonalities\n");
else
printf("%s\n",ans);
}
return 0;
}