Lara Croft, the fiercely independent daughter of a missing adventurer, must push herself beyond her limits when she discovers the island where her father disappeared. In this mysterious island, Lara finds a tomb with a very heavy door. To open the door, Lara must input the password at the stone keyboard on the door. But what is the password? After reading the research notes written in her father's notebook, Lara finds out that the key is on the statue beside the door.
The statue is wearing many arm rings on which some letters are carved. So there is a string on each ring. Because the letters are carved on a circle and the spaces between any adjacent letters are all equal, any letter can be the starting letter of the string. The longest common subsequence (let's call it "LCS") of the strings on all rings is the password. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
For example, there are two strings on two arm rings: s1 = "abcdefg" and s2 = "zaxcdkgb". Then "acdg" is a LCS if you consider 'a' as the starting letter of s1, and consider 'z' or 'a' as the starting letter of s2. But if you consider 'd' as the starting letter of s1 and s2, you can get "dgac" as a LCS. If there are more than one LCS, the password is the one which is the smallest in lexicographical order.
Please find the password for Lara.
输入
There are no more than 10 test cases.
In each case:
The first line is an integer n, meaning there are n (0 < n ≤ 10) arm rings.
Then n lines follow. Each line is a string on an arm ring consisting of only lowercase letters. The length of the string is no more than 8.
输出
For each case, print the password. If there is no LCS, print 0 instead.
样例输入
2
abcdefg
zaxcdkgb
5
abcdef
kedajceu
adbac
abcdef
abcdafc
2
abc
def
样例输出
acdg
acd
0
题意:在n个环形字符串中找最长的公共子字符串,子字符串可以不连续。
思路:首先要将每个字符串复制一下达到环的效果,再依次截取长度为L[i]的连续子字符串。用递归枚举所有出现的字符串的情况,并用map记录。最后在所有字串中判断哪一个出现的次数等于n。
代码如下:
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e6+5;
map<string,int>V[20],A[20];
string s[20];
int L[20],n;
bool work(const string &s,int l,string ss) //在原字符串上截取一个长度为L【i】的串是s,l为这个字串还剩下的长度,ss为拼接的串
{
if(!l)
{
if(!V[ss.size()][ss])
{
V[ss.size()][ss]=++A[ss.size()][ss];//记录每个长度下每种字串出现的次数
}
}
else for(int j=s.size()-l; j<s.size(); ++j) //依次枚举各种字串
work(s,s.size()-j-1,ss+s[j]);
}
int32_t main()
{
while(cin>>n)
{
for(int i=0; i<20; ++i)A[i].clear();
for(int i=0; i<n; ++i)
{
cin>>s[i];
L[i]=s[i].size();
s[i]=s[i]+s[i]; //复制字符串
for(int j=0; j<9; ++j)V[j].clear();//map清空
for(int j=0; j<L[i]; ++j) //截取长度为L[i]的子字符串
work(s[i].substr(j,L[i]),L[i],string(""));
}
int ans=0;
map<string,int>::iterator it;
for(int i=8; i>0; --i)
{
for(it=A[i].begin(); it!=A[i].end();it++)
if(it->second==n)
{
ans=i,i=0;
cout<<it->first<<endl;
break;
}
}
if(!ans)puts("0");
}
return 0;
}