您的位置:首页 > 其它

文章标题

2017-09-16 01:10 337 查看
7-9 旅游规划(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 <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define MAXV 500
#define INF 1000001
typedef struct graph{
int dist[MAXV][MAXV];
int cost[MAXV][MAXV];
int nV,nE;
int s,d;
}Graph;

int Dij(Graph &g){
int i,j;
int dist[MAXV];
int cost[MAXV];
for(i=0;i<g.nV;i++){
dist[i]=g.dist[g.s][i];
cost[i]=g.cost[g.s][i];
}
int visited[MAXV]={};
visited[g.s]=1;
/*
for(j=0;j<g.nV;j++){
printf("%d ",dist[j]);
}putchar('\n');
for(j=0;j<g.nV;j++){
printf("%d ",cost[j]);
}putchar('\n');*/
for(i=0;i<g.nV-1;i++){
int minIndex=0,minValue=INF;
for(j=0;j<g.nV;j++){
if(!visited[j]&&dist[j]<minValue){
minIndex=j;minValue=dist[j];
}
}
visited[minIndex]=1;
for(j=0;j<g.nV;j++){
if(!visited[j]){
if(minValue+g.dist[minIndex][j]<dist[j]){
dist[j]=minValue+g.dist[minIndex][j];
cost[j]=cost[minIndex]+g.cost[minIndex][j];
}else if(minValue+g.dist[minIndex][j]==dist[j]){
if(cost[minIndex]+g.cost[minIndex][j]<cost[j]){
cost[j]=cost[minIndex]+g.cost[minIndex][j];
}
}
}
}
/*
for(j=0;j<g.nV;j++){
printf("%d ",dist[j]);
}putchar('\n');
for(j=0;j<g.nV;j++){
printf("%d ",cost[j]);
}putchar('\n');*/
}
printf("%d %d",dist[g.d],cost[g.d]);
return 0;
}

int main(void){
int i,j;
Graph g;
scanf("%d%d%d%d",&g.nV,&g.nE,&g.s,&g.d);
for(i=0;i<g.nV;i++){
for(j=0;j<g.nV;j++){
if(i!=j){g.dist[i][j]=INF;g.cost[i][j]=INF;}
else{g.dist[i][j]=0;g.cost[i][j]=0;}

}
}
int ts,td,tdist,tcost;
for(i=0;i<g.nE;i++){
scanf("%d%d%d%d",&ts,&td,&tdist,&tcost);
g.dist[ts]=tdist;
g.dist[ts]=tdist;
g.cost[ts]=tcost;
g.cost[ts]=tcost;
}
Dij(g);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: