《数据结构》07-图6 旅游规划

题目

有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。

输入格式:
输入说明:输入数据的第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

分析

权值有两个,用两个图存储就好,最短路径直接上 Dijkstra 算法,稍微改改就 ok

#include<iostream>
#define MaxVertex 505
#define INF 100000
typedef int Vertex;
int N; // 顶点数
int M; // 边
int S; // Source
int D;  // Destination 
int dist[MaxVertex];  // 距离
int cost[MaxVertex]; // 费用
bool collected[MaxVertex];  // 选中情况 
int value[MaxVertex][MaxVertex];  // 收费
int G[MaxVertex][MaxVertex];
using namespace std; 


void build(){
	Vertex v1,v2,w1,w2;
	cin>>N>>M>>S>>D;
	for(Vertex i=0;i<N;i++){
		for(Vertex j=0;j<N;j++){
			G[i][j] = INF;
			value[i][j] = INF; 
		}
		cost[i] = 0;
		collected[i] = false;
		dist[i] = INF;
	}
	for(int i=0;i<M;i++){
		cin>>v1>>v2>>w1>>w2;
		G[v1][v2] = w1;
		G[v2][v1] = w1; 
		value[v1][v2] = w2;
		value[v2][v1] = w2;
	}
}

// 初始化源点信息 
void InitSource(){
	dist[S] = 0;
	collected[S] = true;
	for(Vertex i=0;i<N;i++)
		if(G[S][i]){
			dist[i] = G[S][i];
			cost[i] = value[S][i];
		}
}

// 查找未被收录中dist最小的点 
Vertex FindMin(){
	int min = INF;
	Vertex xb = -1;
	for(Vertex i=0;i<N;i++)
		if(S!=i && !collected[i] && dist[i] < min){
			min = dist[i];
			xb = i;
		}
	return xb;
}

void Dijkstra(){
	InitSource();
	while(1){
		Vertex v = FindMin();
		if(v==-1)
			break;
		collected[v] = true;
		for(Vertex w=0;w<N;w++)
			if(!collected[w] && G[v][w])
				if(dist[v] + G[v][w] < dist[w]){  // 如果有路径更短 
					dist[w] = dist[v] + G[v][w];
					cost[w] = cost[v] + value[v][w];
				}else if(dist[v] + G[v][w] == dist[w] && cost[v] + value[v][w] < cost[w]){  // 如果路径一样长,选择费用更少 
					cost[w] = cost[v] + value[v][w];
				}
	}
}


int main(){
	build();
	Dijstra();
	cout<<dist[D]<<" "<<cost[D];
	return 0;
}

猜你喜欢

转载自blog.csdn.net/liyuanyue2017/article/details/84192009