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

思路:

这个问题在构造图的时候会成为一个双权重的图。以距离为第一优先级,价格为第二优先级,使用dijstra进行单源最短路搜索,分别记录dist和cost_dist数组,dist[i]代表从s出发到i的最短路径,cost_dist[i]代表从s出发到i的最小价格。

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int N = 505;      //最大N  

struct highway{
    int length;
    int price;
}graph[N][N];           //带两个权重的图
int dist[N];            //dist[i]代表城市s到i的最短距离 
int path[N];            //path[i]代表i城市的上一个城市 
int cost_dist[N];       //cost_dist[i]代表从s出发到i的最小价格 
int visited[N]={0};     //visited[i]代表i城市是否被访问过 
void dijstra(int s, int n){
    //初始化dist path
    for(int i = 0; i < n; i++){
        dist[i]=N;
        cost_dist[i]=N;
        if(i==s){
            dist[i]=0;
            cost_dist[i]=0;
        }   
        path[i]=-1;
    } 

    queue<int>q;
    int cur = s;
    q.push(cur);
    while(!q.empty()){
        cur = q.front();
        visited[cur]=1;
        q.pop();
        for(int i=0; i < n; i++){
            if(graph[cur][i].length!=-1&&visited[i]==0){
                //如果当前路径距离更短,更新路径
                    q.push(i);
                    dist[i]=dist[cur]+graph[i][cur].length;
                    cost_dist[i]=cost_dist[cur]+graph[cur][i].price;
                    path[i]=cur;
                }else if(dist[cur]+graph[cur][i].length==dist[i]&&cost_dist[cur]+graph[cur][i].price<cost_dist[i]){
                //如果当前路径距离长度相同且价格更低,更新路径
                    dist[i]=dist[cur]+graph[i][cur].length;
                    cost_dist[i]=cost_dist[cur]+graph[cur][i].price;
                    path[i]=cur;
                }   
            }
        }
    }
}
int main(){
    int n,m,s,d;
    cin>>n>>m>>s>>d;
    //初始化graph 
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++) {
            if(i==j){
                graph[i][j].price=0;
                graph[i][j].length=0;
            }else{
                graph[i][j].price=-1;
                graph[i][j].length=-1;
            }       
        }
    } 
    while(m--){
        int x,y,len,price;
        cin>>x>>y>>len>>price;
        graph[x][y].length=len;
        graph[x][y].price=price; 
        graph[y][x].length=len;
        graph[y][x].price=price; 
    } 
    dijstra(s,n);
    cout<<dist[d]<<" "<<cost_dist[d]<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37513086/article/details/80015906