Road Construction Aizu - 2249 单源最短路

题目链接:Road Construction Aizu - 2249

n座城市,编号1-n,1号为首都,原计划修m条道路,现在要削减成本,取消一些道路,使得成本最小。要求,每个城市都能通往首都,原计划每座城市到首都的最短距离在新计划里面还是不变。

以dist为权值,求最短路,再开一个pre数组,pre[i]表示从首都到i城的最短路中,i城的上一座城市到i城的cost。最后将求出的最短路所有pre加起来就好了

同时,i城到首都的最短路可能有多条,这时pre里面存的是多条最短路径里面cost最小的,所以,当d[e.to] == d[i] + e.dist时,pre[e.to] = min(pre[e.to], e.cost);

WA了一次,因为mn同时为0表示结束,但我判断条件写成了 m&&n,结果出现 1 0 这组数据的时候就会退出,WA

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>

using namespace std;

const int MAXV = 10000 + 100, INF = 0x3f3f3f3f;
int n, m, E, V, a, b, dis, co;
struct edge
{
    int to, dist, cost;
    edge(int a=0, int b=0, int c=0) :to(a), dist(b), cost(c) {}
};
vector<edge> G[MAXV];
int d[MAXV], pre[MAXV];
typedef pair<int, int> P;


int main()
{
    while(scanf("%d%d", &n, &m) == 2 && m+n)//不能写成&&m && n
    {
        E = 0;
        V = n;
        for(int i=0; i<n; ++i) G[i].clear();

        for(int i=0; i<m; ++i)
        {
            scanf("%d%d%d%d", &a, &b, &dis, &co);
            --a; --b;
            G[a].push_back(edge(b, dis, co));
            G[b].push_back(edge(a, dis, co));
        }

        memset(d, 0x3f, sizeof(d));
        memset(pre, 0x3f, sizeof(pre));
        priority_queue<P, vector<P>, greater<P> > que;
        d[0] = 0;
        que.push(P(0, 0));

        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.dist)
                {
                    d[e.to] = d[v] + e.dist;
                    que.push(P(d[e.to], e.to));
                    pre[e.to] = e.cost;
                }
                else if(d[e.to] == d[v] + e.dist)
                {
                    pre[e.to] = min(pre[e.to], e.cost);
                }
            }
        }
        int ans = 0;
        for(int i=1; i<n; ++i) ans += pre[i];
        cout << ans << endl;
    }

    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值