floyd算法实现
来源:互联网 发布:淘宝商品标题优化方法 编辑:程序博客网 时间:2024/05/21 04:22
#include<iostream>#include<iomanip>#include<vector>using namespace std;const int Max=100;const int INF=5000;class Graph{public:/* data */ int VertexNum;//一个图的点数 int Edgeweight[Max][Max];//每条边的权值 bool type;//有向图还是无向图 int edgenum;//图的边数 char Vertexname[Max];//图中点的名称 int shortest[Max][Max];//记录最短路径的长度int parent[Max][Max];//存储最短路径所经过的点 Graph() { for (int i = 0; i < Max; ++i) { for (int j = 0; j <Max; ++j) { /* code */parent[i][j]=-1; } } }};void floyd(Graph *g){ for (int i = 0; i < g->VertexNum; ++i) { /* code */ for (int j = 0; j < g->VertexNum; ++j) { /* code */ if(i!=j)g->shortest[i][j]=g->Edgeweight[i][j];elseg->shortest[i][j]=0;//cout<<g->shortest[i][j]<<" ";cout<<g->Edgeweight[i][j]<<" "; g->parent[i][j]=-1; } cout<<endl; }for (int i = 0; i < g->VertexNum; ++i){/* code */for (int j= 0; j < g->VertexNum; ++j){/* code */for (int k = 0; k < g->VertexNum; ++k){/* code */ cout<<g->shortest[i][j]<<" "<<g->shortest[i][k]+g->shortest[k][j]<<" "; if(g->shortest[i][j]==INF) g->shortest[i][j]=g->shortest[i][k]+g->shortest[k][j]; else if(g->shortest[i][j]>(g->shortest[i][k]+g->shortest[k][j])) { g->shortest[i][j]=g->shortest[i][k]+g->shortest[k][j]; g->parent[i][j]=k; } cout<< g->shortest[i][j]<<endl; } } }}int main(){ Graph g; cout<<"the graph is no direction (enter 0) , or direction (enter 1)"<<endl; cin>>g.type; int d[Max][Max]; cout<<"please input the number of edges and VertexNum"<<endl; cin>>g.edgenum>>g.VertexNum; for (int i = 0; i < g.VertexNum; ++i) { /* code */ cout<<"the "<<i+1<<" th"<<"Vertex's name is :"<<endl; cin>>g.Vertexname[i]; } cout<<"please input the info of edge like A B 5 "<<endl; for (int i = 0; i < g.VertexNum; ++i) { /* code */ for (int j = 0; j < g.VertexNum; ++j) { /* code */ if(i==j) g.Edgeweight[i][j]=0; else g.Edgeweight[i][j]=INF; } } for (int i = 0; i < g.edgenum; ++i) { /* code */ char a,b; int weight; cin>>a>>b>>weight; int index,index2; for (index = 0;g.Vertexname[index]!=a;index++); for (index2= 0;g.Vertexname[index2]!=b;index2++); /* code */ g.Edgeweight[index][index2]=weight; if(g.type==0) g.Edgeweight[index2][index]=weight; } floyd(&g); for (int i = 0; i < g.VertexNum; ++i) { cout<<setw(7)<<g.Vertexname[i]; } cout<<endl; for (int i = 0; i < g.VertexNum; ++i) { /* code */ cout<<g.Vertexname[i]; for (int j = 0; j < g.VertexNum; ++j) { /* code */ if(g.shortest[i][j]>=INF) cout<<setw(7)<<"Z"; else cout<<setw(7)<<g.shortest[i][j]; } cout<<endl; } for (int i = 0; i < g.VertexNum; ++i) { /* code */ cout<<g.Vertexname[i]; std::vector<int> v; for (int j = 0; j < g.VertexNum; ++j) { if(g.shortest[i][j]>=Max||i==j) continue; int temp=g.parent[i][j]; while(temp!=-1) { v.push_back(g.parent[i][j]); temp=g.parent[i][temp]; } for (int s= 0; s < v.size(); ++s) { /* code */ cout<<v[s]<<" "; } cout<<endl; } }system("pause");return 0;}/*11571 2 3 4 5 6 7 1 2 41 3 52 3 62 4 32 5 103 4 44 3 33 6 94 6 55 4 4 4 5 35 6 36 5 25 7 26 7 2*/