07-图6 旅游规划 (25分)

07-图6 旅游规划 (25分)

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

输入格式:

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

#include
using namespace std;

#define INFINITY 65535
struct MNode{
	int Nv;
	int Ne;
	int Vertex[505][505];
}; 
int path[505],price[505][505],dist[505],pc[505]={0};
bool collected[505]={false};
typedef struct MNode* MGraph;

MGraph Create(int N,int V){
	int v,w,len,price1;
	MGraph Graph=(MGraph)malloc(sizeof(struct MNode));
	Graph->Nv=N;
	Graph->Ne=V;
	for(int i=0;i<Graph->Nv;i++){
		for(int j=0;j<Graph->Nv;j++){
			if(i==j) Graph->Vertex[i][j]=0;
			else Graph->Vertex[i][j]=INFINITY;
		}
	}
	for(int i=0;i<Graph->Ne;i++){
		cin>>v>>w>>len>>price1;
		Graph->Vertex[v][w]=len;
		Graph->Vertex[w][v]=len;
		price[v][w]=price[w][v]=price1;
	}
	return Graph;
}

int FindMin(MGraph Graph){
	int min=INFINITY,MinV;
	
	for(int i=0;i<Graph->Nv;i++){
		if(collected[i]==false&&dist[i]<min){
			min=dist[i];
			MinV=i; 
		}
	}
	if(min==INFINITY)
		return -1;
	else return MinV; 
}
void Dijkstra(MGraph Graph,int S){
	
	int V;
	for(int i=0;i<Graph->Nv;i++){
		path[i]=-1;
		dist[i]=INFINITY;
		collected[i]=false;
	}
	
	collected[S]=true;
	dist[S]=0;
	
	for(int i=0;i<Graph->Nv;i++){
		if(collected[i]==false&&Graph->Vertex[S][i]<INFINITY){
			dist[i]=Graph->Vertex[S][i];
			path[i]=S;
			pc[i]+=price[S][i];
		}
	}
	
	while(1){
		V=FindMin(Graph);
		if(V==-1)
			break;
		collected[V]=true;
		for(int i=0;i<Graph->Nv;i++){
			if(collected[i]==false&&dist[i]>dist[V]+Graph->Vertex[V][i]){
				dist[i]=dist[V]+Graph->Vertex[V][i];
				pc[i]=pc[V]+price[V][i];
				path[i]=V;
			}else if(collected[i]==false&&dist[i]==dist[V]+Graph->Vertex[V][i]){
				if(pc[i]>pc[V]+price[V][i]){
					pc[i]=pc[V]+price[V][i];
					path[i]=V;
				}
			}
		}
	}
}

int main(){
	int N,V,S,last,price1=0;
	cin>>N>>V>>S>>last;
	MGraph Graph=Create(N,V);
	Dijkstra(Graph,S);
	printf("%d %d",dist[last],pc[last]);
}

你可能感兴趣的:(图)