#include <iostream>
#include <string>
using namespace std;
typedef struct Graph
{
string vertex[10];
int arc[10][10];
int num_vertex;
int num_edge;
}Graph;
int get_location(Graph g, string s)
{
int i;
for(i=0;i<g.num_vertex;i++)
{
if(s == g.vertex[i])
return i;
}
return -1;
}
void create_graph(Graph &g)//创建有向图
{
int i,j,k,w;
string s1,s2;
cout<<"请输入顶点数和边数:";
cin>>g.num_vertex>>g.num_edge;
cout<<"请输入顶点:";
for(i=0;i<g.num_vertex;i++)
cin>>g.vertex[i];
for(i=0;i<g.num_vertex;i++)
for(j=0;j<g.num_vertex;j++)
g.arc[i][j]=65535;
cout<<"请输入边和对应的权值:"<<endl;
for(k=0;k<g.num_edge;k++)
{
cin>>s1>>s2>>w;
i = get_location(g,s1);
j = get_location(g,s2);
g.arc[i][j]=w;
}
}
void shortpath_dijkstra(Graph g, int v, int p[], int d[])
{
int i,j,k,min;
bool final[10];//标识是否已经求得最短路径
for(i=0;i<g.num_vertex;i++)//初始化
{
final[i]=false;
p[i]=v;
d[i]=g.arc[v][i];
}
final[v]=true;
d[v]=0;
for(i=1;i<g.num_vertex;i++)
{
min=65535;
for(j=0;j<g.num_vertex;j++)
{
if(!final[j] && d[j]<min)
{
k=j;
min=d[j];
}
}
final[k]=true;
for(j=0;j<g.num_vertex;j++)
{
if(!final[j] && (d[j]>min+g.arc[k][j]))
{
d[j] = min+g.arc[k][j];
p[j] = k;
}
}
}
}
void print_path_core(Graph g, int v, int i, int p[])
{
if(i==v)
{
cout<<g.vertex[i]<<" ";
return;
}
print_path_core(g,v,p[i],p);
cout<<g.vertex[i]<<" ";
}
void print_path(Graph g, int v, int p[], int d[])
{
cout<<g.vertex[v]<<"到各个顶点的最短路径及长度为:"<<endl;
int i;
for(i=0;i<g.num_vertex;i++)
{
if(i==v)
continue;
if(d[i]==65535)
{
cout<<g.vertex[v]<<"->"<<g.vertex[i]<<"不可达!"<<endl;
}
else
{
cout<<g.vertex[v]<<"->"<<g.vertex[i]<<"的最短路径长度为:"<<d[i]<<" ";
cout<<"最短路径为:";
print_path_core(g,v,i,p);
cout<<endl;
}
}
}
int main()
{
Graph g;
create_graph(g);
string s;
cout<<"请输入从哪个顶点出发:";
cin>>s;
int v = get_location(g,s);
int patharc[10];//存储最短路径下标
int shortpath[10];//存储最短路径的长度
shortpath_dijkstra(g,v,patharc,shortpath);
print_path(g,v,patharc,shortpath);
return 0;
}