因为数据范围很小,所以可以直接暴力。用二进制枚举所有子串,找出所有在每一个字符串中都出现过的子串,找出其中最长且字典序最小的。
#include<stdio.h>
#include<iostream>
#include<map>
#include<string.h>
#include<string>
using namespace std;
map<string,int> m;
char str[20];
void substr()
{
map<string,int> t;
int len = strlen(str);
for(int i = 0;i < len;i++)
{
str[i + len] = str[i];
}
int c = 2<<(len-1);
char sub[20];
for(int i = 0;i < len;i++)
{
for(int j = 1;j < c;j++)
{
int tmp = j,k = i,cnt = 0;
while(tmp)
{
if(tmp%2 == 1)
{
sub[cnt++] = str[k];
}
k++;
tmp /= 2;
}
sub[cnt]='\0';
if(t[sub]==0)
{
m[sub]++;
t[sub]++;
}
}
}
}
int main()
{
int n;
char ans[20];
while(scanf("%d",&n)!=EOF)
{
m.clear();
for(int i = 1;i <= n;i ++)
{
scanf("%s",str);
substr();
}
map<string,int>::iterator it;
string max;
int maxlen = 0;
for(it = m.begin();it != m.end();it ++)
{
if(it->second == n)
{
int len = it->first.length();
if(len > maxlen)
{
maxlen = len;
max = it->first;
}
}
}
if(maxlen != 0)
{
cout<<max<<endl;
}
else
cout<<"0"<<endl;
}
}