HDU 3790 最短路径问题

题目

给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。

Input

输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。 
(1<n<=1000, 0<m<100000, s != t)

Output

输出 一行有两个数, 最短距离及其花费。 

Sample Input

3 2
1 2 5 6
2 3 4 5
1 3
0 0

Sample Output

9 11

 

题解

 板子题

 

AC代码

 

#include <iostream>
#include <vector>
#include <utility>
#include <queue>
#include <algorithm>
using namespace std;

const int INF = 0x3f3f3f3f;

struct edge{
    int to, len, cost;
    edge(int _to, int _len, int _cost):to(_to), len(_len), cost(_cost){}
};
typedef pair<int, int> node;

vector<edge> G[1010];
int dis[1010];
int cost[1010];

void dij(int s){
    fill(dis, dis + 1010, INF);
    fill(cost, cost + 1010, INF);
    dis[s] = 0; cost[s] = 0;
    priority_queue<node, vector<node>, greater<node> > q;
    q.push(node(0, s));
    while(!q.empty()){
        node temp = q.top(); q.pop();
        if(temp.first > dis[temp.second]) continue;
        for(int i = 0; i < G[temp.second].size(); ++i){
            edge e = G[temp.second][i];
            if(dis[e.to] > temp.first + e.len){ // ??
                dis[e.to] = temp.first + e.len;
                cost[e.to] = cost[temp.second] + e.cost;
                q.push(node(dis[e.to], e.to));
                continue;
            }
            if(dis[e.to] == temp.first + e.len){
                if(cost[e.to] > cost[temp.second] + e.cost){
                    cost[e.to] = cost[temp.second] + e.cost;
                    q.push(node(dis[e.to], e.to));
                }
            }
        }
    }
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, m;
    while(cin >> n >> m){
        if(!n && !m) break;
        int a, b, d, p;
        for(int i = 1; i <= 1005; ++i)
            G[i].clear();
        for(int i = 0; i < m; ++i){
            cin >> a >> b >> d >> p;
            G[a].push_back(edge(b, d, p));
            G[b].push_back(edge(a, d, p));
        }
        int s, e; cin >> s >> e;
        dij(s);
        cout << dis[e] << " " << cost[e] << endl;
    }
    return 0;
}

 

posted @ 2019-08-02 09:15  Cl0ud_z  阅读(93)  评论(0编辑  收藏  举报