C++最優路徑之佛洛依德演算法
阿新 • • 發佈:2019-02-11
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
class Graph{
private:
int **matrix;
int vexnum;
string *name;
public:
Graph(string str[], int vnum){
vexnum = vnum;
name = new string[vexnum];
for(int i = 0; i < vexnum; i++)
name[i] = str[i];
matrix = new int*[vnum];
for (int i = 0; i < vexnum; i++) {
matrix[i] = new int [vexnum];
for (int j = 0; j <vexnum; j++)
cin>>matrix[i][j];
}
}
void floyd(){
string **path = new string*[vexnum];
for(int i = 0; i<vexnum;i++) {
path[i] = new string[vexnum];
for (int j = 0;j<vexnum;j++)
if(i==j)
path[i][j] = name[i];
else
path[i][j] = name[i]+name[j];
}
int dis[vexnum][vexnum];
for(int i = 0; i<vexnum;i++)
for (int j=0; j <vexnum;j++)
dis[i][j] = matrix[i][j];
for(int k = 0; k < vexnum; k++)
for(int i = 0; i < vexnum; i++)
for(int j = 0; j <vexnum; j++){
if (dis[i][k] == -1||dis[k][j] == -1)
continue;
if (i!=j){
if(dis[i][j] == -1 || dis[i][j]>dis[i][k]+dis[k][j]){
dis[i][j] = dis[i][k]+dis[k][j];
//節點i到j最短路徑為path[i][k]加path[k][j],中間有重複的k節點,所以要截去
path[i][j] = path[i][k].substr(0,path[i][k].length() - 1) + path[k][j];
}
}
}
cout<<vexnum<<endl;
for (int i = 0; i <vexnum;i++){
if (i!=0)
cout<<' ';
cout<<name[i];
}
cout<<endl;
for(int i = 0;i<vexnum;i++){
for (int j = 0; j<vexnum;j++){
if(j!=0)
cout<<' ';
cout<<path[i][j];
}
cout<<endl;
}
}
};
int main(){
int n;
cin>>n;
string *str = new string[n];
for(int i = 0;i<n;i++)
cin>>str[i];
Graph G(str,n);
G.floyd();
return 0;
}
/*測試資料(有向圖)
輸入
4
a b c d
0 1 -1 7
2 0 2 -1
-1 -1 0 2
1 3 -1 0
輸出
4
a b c d
a ab abc abcd
ba b bc bcd
cda cdab c cd
da dab dabc d
*/