样例输入: ABCC ABCD BCCE BCDE CCEF BCCE CCEG CEGF
样例输出: ABCCEGF
#include <iostream>
#include <string>
using namespace std;
using std::string;
void maxCatenat(string text[],const int n){
int **G = new int*[n];
for(int i=0;i<n;i++){
G[i] = new int[n]();
}
for(int i=0;i<n;i++){
string substr = text[i].substr(1);
for(int j=0;j<n;j++){
if(text[j].find(substr)==0)
G[i][j]=1;
}
}
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(G[i][k]!=0&&G[k][j]!=0){
int dist = G[i][k]+G[k][j];
if(dist>G[i][j])
G[i][j] = dist;
}
}
}
}
for(int i=0;i<n;i++){
if(G[i][i]>1){
cout<<"circle exist"<<endl;
return;
}
}
int maxdis = 0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
maxdis = std::max(maxdis,G[i][j]);
}
}
cout<<"max dis is:"<<maxdis<<endl;
}
void main(){
string text[] ={
"abcd",
"bcde",
"cdea",
"deab",
"eaba",
"abab",
"deac",
"cdei",
"bcdf",
"cdfi",
"dfic",
"cdfk",
"bcdg"
};
int n =sizeof(text)/sizeof(string);
maxCatenat(text,n);
}
//#include <iostream>
//#include <string>
//#include <cctype>
//
//using namespace std;
//
//int main( void )
//{
//
//
// return 0;
//}
//有n个长为m+1的字符串,如果某个字符串的最后m个字符与某个字符串的前m个字符匹配,
//
//则两个字符串可以联接,问这n个字符串最多可以连成一个多长的字符串,如果出现循环,则返回错误。
//
//
//
//思路 :分析一下,将各个字符串作为一个节点,首尾链接就好比是一条边,将两个节点连接起来,于是问题就变
//
//成一个有关图的路径长度的问题。链接所得的字符串最长长度即为从图的某个节点出发所能得到的最长路
//
//径问题,与最短路径类似,可以应用弗洛伊德算法求解。对于循环,即可认为各个节点通过其他节点又回
//
//到自己,反应在路径长度上,就表示某个节点到自己节点的路径大于零(注:初始化个节点到自己的长度为零)。
//#include<iostream>
//#include<string>
//using namespace std;
//
//#define length 14
//
//bool Isconnect(string str1,string str2)
//{
// if(str1.size()!=str2.size())
// return false;
// int m=str1.size();
// for(int i=0;i<m-1;i++)
// {
// if(str1[i+1]!=str2[i])
// return false;
// }
// return true;
//
//
//}
//
//void Maxstring(string str[])
//{
// int G[length][length]={0};
// for(int i=0;i<length;i++)
// for(int j=0;j<length;j++)
// if(Isconnect(str[i],str[j]))
// G[i][j]=1;
// for(int i=0;i<length;i++)
// for(int j=0;j<length;j++)
// for(int k=0;k<length;k++)
// {
// if(G[i][k]!=0&&G[k][j]!=0)
// {
// int dis=G[i][k]+G[k][j];
// if(dis>G[i][j])
// G[i][j]=dis;
//
// }
// }
// for(int i=0;i<length;i++)
// if(G[i][i]>1)
// {
// cout<<"circle is deteted"<<endl;
// return;
// }
// int max=0;
// for(int i=0;i<length;i++)
// for(int j=0;j<length;j++)
// {
// if(G[i][j]>max)
// max=G[i][j];
//
// }
// cout<<"Max length is "<<max+str[0].size()<<endl;
//
//}
//
//
//
//int main()
//{
// string str[length]={
// "abcd",
// "bcde",
// "cdea",
// "deab",
// "eaba",
// "abab",
// "deac",
// "cdei",
// "bcdf",
// "cdfi",
// "dfic",
// "cdfk",
// "bcdg" };
// //"babc"};
// Maxstring(str);
//
//}