有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。
输出格式:
在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
输出样例:
3 40
用floyd算法可以直接得到各点间的最短路径,关键点在于如何选择在具有多条最短路径时,选择花费最小的路径。其实这也是一个求最短路径的过程,只是它具有一个前提条件就是‘’在路程为最短‘’。这样就可以稍微改动一下原floyd里面的语句即可。
#include<stdio.h>
#include<stdlib.h>
#define INFINITY 65535
#define MAX 501
typedef int WeightType;
typedef int DataType;
typedef int Vertex;
typedef struct GNode{
int Nv,Ne;
WeightType G[MAX][MAX]; //记录城市之间的高速路的距离的邻接举证
DataType G1[MAX][MAX]; //记录城市之间的高速路的花费的邻接矩阵
}PtrToGNode,*MGraph;
typedef struct ENode{
Vertex V1,V2;
WeightType Weight;
DataType Data;
}PtrToENode,*Edge;
MGraph CreateGraph(int VertexNum){
MGraph graph;
graph = (MGraph)malloc(sizeof(struct GNode));
graph->Nv = VertexNum;
graph->Ne = 0;
Vertex V, W;
for(V=0; V<graph->Nv; V++)
for(W=0; W<graph->Nv; W++)
graph->G[V][W] = INFINITY;
return graph;
}
void InsertEdge(MGraph graph, Edge E){
Vertex V = E->V1;
Vertex W = E->V2;
graph->G[V][W] = E->Weight;
graph->G[W][V] = E->Weight;
graph->G1[V][W] = E->Data;
graph->G1[W][V] = E->Data;
}
int D[MAX][MAX];
int Cost[MAX][MAX];
int Path[MAX][MAX];
void Floyd(MGraph graph){
int i, j, k;
for(i=0; i<graph->Nv; i++){
for(j=0; j<graph->Nv; j++){
D[i][j] = graph->G[i][j];
Cost[i][j] = graph->G1[i][j];
Path[i][j] = -1;
}
}
for(k=0; k<graph->Nv; k++){
for(i=0; i<graph->Nv; i++){
for(j=0; j<graph->Nv; j++){
if(D[i][k]+D[k][j]<D[i][j]||(D[i][k]+D[k][j]==D[i][j]&&
Cost[i][k]+Cost[k][j]<Cost[i][j])){//路径相等时,且话费更少时,更新路径
D[i][j] = D[i][k]+D[k][j];
Path[i][j] = k;
Cost[i][j] = Cost[i][k]+Cost[k][j];
}
}
}
}
}
int a[MAX];
int num = 1;
void ThePath(Vertex V, Vertex W){
Vertex S = Path[V][W];
if(S==-1){
return;
}
ThePath(V, S);
a[num++] = S;
ThePath(S, W);
}
int main(){
int N, M;
Vertex V, W;
scanf("%d%d%d%d",&N, &M, &V, &W);
MGraph graph = CreateGraph(N);
graph->Nv = N;
graph->Ne = M;
Vertex i;
Edge E;
for(i=0; i<M; i++){
E = (Edge)malloc(sizeof(struct ENode));
scanf("%d%d%d%d",&E->V1,&E->V2,&E->Weight,&E->Data);
InsertEdge(graph, E);
}
Floyd(graph);
printf("%d%d",D[V][W],Cost[V][W]);
return 0;
}