题目链接: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;
}