#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];
else
g->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;
}
/*
1
15
7
1 2 3 4 5 6 7
1 2 4
1 3 5
2 3 6
2 4 3
2 5 10
3 4 4
4 3 3
3 6 9
4 6 5
5 4 4
4 5 3
5 6 3
6 5 2
5 7 2
6 7 2
*/
floyd算法实现
最新推荐文章于 2023-06-17 23:28:06 发布