有n 个长为m+1 的字符串,
如果某个字符串的最后m 个字符与某个字符串的前m 个字符匹配,则两个字符串可以联接,
问这n 个字符串最多可以连成一个多长的字符串,如果出现循环,则返回错误
//-------------------------------------
这道题可以使用图的方法来求解,能相连的点看成是中间有一条连线,最后简化为先构建一个图,然后从图中查找最长路径,如果出现环,报错。
#include "loop.h"
#include <vector>
#include <string>
#include <iostream>
#include <deque>
using namespace std;
int LongestPath(int* graph, int n, int * indeep )
{
int max = 0;
bool* visit = (bool*) malloc(sizeof(bool) * n);
memset(visit, 0, sizeof(bool) * n);
deque<int> point;
for (int i = 0; i < n; i++)
{
//find the first indeep is zero behind i
while(i < n && indeep[i]) i++;
if (i == n)
break;
//use width first to find the longest path
int pathlong = 0;
point.clear();
point.push_back(i);
point.push_back(-1);
memset(visit, 0, sizeof(bool) * n);
visit[i] = true;
while(!point.empty())
{
int index = point.front();
point.pop_front();
if(index < 0)
{
if (!point.empty())
{
point.push_back(-1);
pathlong++;
}
}
else
{
for(int j = 0; j < n; j++)
{
if (graph[ index*n + j] )
{
if(!visit[j]){
point.push_back(j);
visit[j] = true;
}else{
cout<<"there is a loop"<<endl;
return -1;
}
}
}
}
}
if(pathlong > max)
max = pathlong;
}
free(visit);
return max;
}
/*
有n 个长为m+1 的字符串,
如果某个字符串的最后m 个字符与某个字符串的前m 个字符匹配,则两个字符串可以联接,
问这n 个字符串最多可以连成一个多长的字符串,如果出现循环,则返回错误。
*/
int LongestConection(vector<string> bag, int m)
{
int n = bag.size();
//initial graph
int* graph = (int*) malloc(sizeof(int) * n * n);
memset( graph, 0, sizeof(int) * n * n);
int* indeep = (int*) malloc(sizeof(int) * n);
memset(indeep, 0, sizeof(int)*n);
for(int i = 0; i < n; i++)
for(int j = 0; j <n; j++)
{
if (j != i && strncmp(bag[i].c_str()+1, bag[j].c_str(), m) == 0)
{
graph[i*n+j] = 1;
indeep[j]++;
}
}
int result = LongestPath(graph, n, indeep);
free(graph);
free(indeep);
if (result < 0)
return -1;
return result + m+1;
}
int main()
{
vector<string> bag;
bag.push_back("abc");
bag.push_back("bcd");
bag.push_back("cda");
int m = 2;
int result = LongestConection(bag, m);
if ( result < 0){
cout<<"there is a loop "<<endl;
return 0;
}
cout<<"the longest connect is : "<<result<<endl;
getchar();
return 0;
}