ZOJ 3946 Highway Project(多属性边权最短路)

题目链接:

题意:
有n个城市编号从0–n-1,其中编号为0的城市是首都,有m条无向边,每条边有两个属性走过这条路径的time和建造这条路径的cost,求从首都出发到达其他各个城市的最少时间和最少cost?(优先时间最少)
分析;
首先需要明确在满足到达各个城市最少时间情况下若干条边的cost之和而不是到达各个城市的cost之和!
最少时间是求一次最短路,然后在求最短路的时候判断如果有多条最短路取边cost权最少的一个作为到达这个城市的cost,最终答案是各个城市的time和cost累加。(time是从源点出发到达这个城市的最少时间)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#include <queue>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 100010;

int T, n, m, total;
int vis[MAX_N], head[MAX_N * 2];

struct Edge{
    int to, next;
    ll cost, tim;
}edge[MAX_N * 2];

struct HeapNode{
    int u;
    ll tim, cost;
    bool operator < (const HeapNode& rhs) const {
        if(tim != rhs.tim) return tim > rhs.tim;
        else return cost > rhs.cost;
    } 
};

HeapNode ans[MAX_N];

void AddEdge(int from, int to, ll tim, ll cost)
{
    edge[total].to = to;
    edge[total].tim = tim;
    edge[total].cost = cost;
    edge[total].next = head[from];
    head[from] = total++;
}

void Dijkstra()
{
    priority_queue <HeapNode> Q;
    while(!Q.empty()) Q.pop();
    for(int i = 0; i < n; i++){
        ans[i].u = i;
        ans[i].tim = ans[i].cost = (ll)INT_MAX * 100; //初始化一开始是INT_MAX,结果WA了好多发!!!
    }
    ans[0].tim = ans[0].cost = 0;
    Q.push(ans[0]);
    memset(vis, 0, sizeof(vis));
    while(!Q.empty()){
        HeapNode x = Q.top();
        Q.pop();
        int u = x.u;
        if(vis[u]) continue;
        vis[u] = 1;
        for(int i = head[u]; i != -1; i = edge[i].next){
            int v = edge[i].to;
            ll t = edge[i].tim;
            ll c = edge[i].cost;
            if(ans[v].tim > ans[u].tim + t || (ans[v].tim == ans[u].tim + t && ans[v].cost > c)){
                ans[v].tim = ans[u].tim + t;
                ans[v].cost = c;
                //cout << u << "-->" << v << ":" << ans[v].tim << endl;
                Q.push(ans[v]);
            }
        }
    }
}

int main()
{
    IOS;
    cin >> T;
    while(T--){
        cin >> n >> m;
        memset(head, -1, sizeof(head));
        total = 0;
        for(int i = 0; i < m; i++){
            int a, b;
            ll c, d;
            cin >> a >> b >> c >> d;
            AddEdge(a, b, c, d);
            AddEdge(b, a, c, d);
        }
        Dijkstra();
        ll res1 = 0, res2 = 0;
        for(int i = 1; i <= n - 1; i++){
            res1 += ans[i].tim;
            res2 += ans[i].cost;
        }
        cout << res1 << " " << res2 << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值