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

来源:互联网 发布:java与安卓 编辑:程序博客网 时间:2024/06/01 08:40

题目链接:

题意:
有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