数据结构实验之图论七:驴友计划 SDUOJ(最短路优化+变形)

 

 在路径相同的情况下,选择钱最少的,只需要加一个变量 w就可以了。

#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
typedef long long ll;
#define pb push_back
const int N = 510;
int INF = 1e9+10;
struct node{
    int now, d, w;
    bool friend operator<(const node& a, const node& b) {
        if(a.d != b.d) return a.d > b.d;
        else a.w > b.w;
    }
};
priority_queue<node>que;
struct Info{
    int to, d, w;
};
vector<Info> E[N];
int dis[N], cost[N];
int n, m, S, D;
void dijkstra()
{
    for(int i = 0; i <= n; ++i) {
        dis[i] = INF;
        cost[i] = INF;
    }
    dis[S] = cost[S] = 0;
    que.push({S, dis[S], cost[S]});
    while(!que.empty()) {
        int now = que.top().now;   //当前到达的最短的那个点。
        que.pop();
        int _size = E[now].size();
        for(int i = 0; i < _size; ++i) {
           Info info = E[now][i];  //取出和now相连的点。
           if(dis[info.to] > dis[now] + info.d) {   //info.d  to和now的距离. dis[now] 从起点到now点的距离. dis[info.to] 从起点到info.to点的距离
                dis[info.to] = dis[now] + info.d;
                cost[info.to] = cost[now] + info.w;     //更新
                que.push({info.to, dis[info.to], cost[info.to]});
           }else if(dis[info.to] == dis[now] + info.d) {
                cost[info.to] = cost[now] + info.w;   //更新
                que.push({info.to, dis[info.to], cost[info.to]});
           }
        }
    }
    printf("%d %d\n", dis[D], cost[D]);
}

void solve()
{
    int T;
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d%d%d", &n, &m, &S, &D);
        for(int i = 1; i <= m; i++) {
            int u, v, d, w;
            scanf("%d%d%d%d", &u, &v, &d, &w);
            E[u].pb({v, d, w});
            E[v].pb({u, d, w});
        }

        dijkstra();
        for(int i = 0; i < n; ++i) E[i].clear();
        while(!que.empty()) que.pop();
    }
}
int main()
{
    solve();
    return 0;
}
View Code

 

posted @ 2020-10-24 13:25  Swelsh-corgi  阅读(238)  评论(0编辑  收藏  举报