图论:07-图6 旅游规划 (Dijstra算法)

题目如下:

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

输入格式:

输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。

输出格式:

在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例1:

4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20

输出样例1:

4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20

输入样例2:

2 1 0 1
0 1 2 3

输出样例2:

在这里插入代码片

2 3

#include //这段代码只能用来做pta上的题,遇到数据更多的可能会不通过,需要进行优化
#include 
#include
#include
#include
using namespace std;
int pa,pb,pc,pd; 
struct node{
	int from;
	int to;
	int length;
	int cost;
}kkk[1000000+5];
int collect[505];
int dist[505];
int costs[505];
int n,m,s,d;
int FindMinDist(int dist[], int collect[] )
{
    int MinV, V;
    int MinDist = 1e9;
    for (V=0; V<n; V++) {
        if ( collect[V]==false && dist[V]<MinDist) {
            MinDist = dist[V]; 
            MinV = V; 
        }
    }
    if (MinDist < 1e9) 
        return MinV;
    else return -1;
}
int main()
{	
	memset(collect,0,sizeof(collect));
	for(int i=0;i<505;i++) dist[i]=1e9;
	for(int i=0;i<505;i++) costs[i]=1e9;
	scanf("%d%d%d%d",&n,&m,&s,&d);
	dist[s]=0;
	costs[s]=0;
	for(int i=0;i<2*m;i++){
		scanf("%d%d%d%d",&pa,&pb,&pc,&pd);
		kkk[i].from=pa;kkk[i].to=pb;kkk[i].length=pc;kkk[i].cost=pd;
		i++;
		kkk[i].from=pb;kkk[i].to=pa;kkk[i].length=pc;kkk[i].cost=pd;
	}
	while(1){
		int v=FindMinDist(dist,collect);
		if(v==-1) break;
		collect[v]=1;
		for(int i=0;i<2*m;i++){
			if(kkk[i].from==v && collect[kkk[i].to]==0){
				if(dist[v]+kkk[i].length<dist[kkk[i].to]){
					dist[kkk[i].to]=dist[v]+kkk[i].length;
					costs[kkk[i].to]=costs[v]+kkk[i].cost;
				}
				else if( dist[v]+kkk[i].length == dist[kkk[i].to] && costs[v]+kkk[i].cost<costs[kkk[i].to]){
					costs[kkk[i].to]=costs[v]+kkk[i].cost;
				}
			}
		}
	}
	printf("%d %d",dist[d],costs[d]);
    return 0;
}

你可能感兴趣的:(图论)