7-10(图) 旅游规划

7-10(图) 旅游规划(25 分)

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

输入格式:

输入说明:输入数据的第1行给出4个正整数NMSD,其中N2N500)是城市的个数,顺便假设城市的编号为0~(N1);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 <bits/stdc++.h>
using namespace std;
const int maxn = 505;
const int INF = 0x3f3f3f3f;
struct Edge
{
    int to,cost,money;
    Edge(int cost_,int to_,int money_)
    {
        to = to_;
        cost = cost_;
        money = money_;
    }
};
typedef pair<int,int>P;
int v,n,st,ed;
vector<Edge>g[maxn];
int d[maxn],m[maxn];

void dijkstra(int s)
{
    priority_queue<P, vector<P> , greater<P> > que;
    fill(d,d+v,INF);fill(m,m+v,INF);
    d[s] = 0;
    m[s] = 0;
    que.push(P(0,s));
    while(!que.empty())
    {
        P p = que.top();que.pop();
        int v = p.second;
        if(d[v] < p.first) continue;
        for(int i = 0 ; i < g[v].size() ; i++)
        {
            Edge& e = g[v][i];
            if(d[e.to] > d[v] + e.cost)
            {
                m[e.to] = m[v] + e.money;
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to],e.to));
            }
            else if(d[e.to] == d[v] + e.cost)
            {
                m[e.to] = min(m[v] + e.money,m[e.to]);
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to],e.to));
            }
        }
    }
}
int main()
{
    scanf("%d%d%d%d",&v,&n,&st,&ed);
    for(int i = 0; i < n ; i++)
    {
        int from,to,cost,money;
        scanf("%d%d%d%d",&from,&to,&cost,&money);
        g[from].push_back(Edge(cost,to,money));
        g[to].push_back(Edge(cost,from,money));
    }
    dijkstra(st);
    printf("%d %d\n",d[ed] , m[ed]);
    return 0;
}

作者: 陈越
单位: 浙江大学
时间限制: 400ms
内存限制: 64MB
代码长度限制: 16KB



猜你喜欢

转载自blog.csdn.net/zhaiqiming2010/article/details/78773047