Aizu

思路:题目要求所有点到1号点最小距离不变,所以我们采用单源最短路。考虑spfa,对于每一个点来说都是被更新,我们只要记住在这些更新该点的边里

dist最短且cost尽量小的,而且这张图到最后一定是一棵树,我们只需要记录下每个cost[i],最后整体相加就行了。

详见代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 10005;
const int F = 0x3f;
const int INF = 0x3f3f3f3f;

struct edge{
    int to,dist,cost;
    edge(int a = 0,int b = 0,int c = 0){
        to = a,dist = b,cost = c;
    }
};

vector<edge> graph[maxn];
int dist[maxn],len[maxn],N,M;
bool inque[maxn];

int spfa(int s){
    memset(dist,F,sizeof(dist));
    memset(len,F,sizeof(len));
    memset(inque,false,sizeof(inque));
    dist[s] = len[s] = 0;
    queue<int> que;
    que.push(s);
    inque[s] = true;
    while(que.size()){
        int temp = que.front();
        que.pop();
        inque[temp] = false;
        for(int i = 0;i < graph[temp].size();++i){
            edge& e = graph[temp][i];
            int to = e.to,d = e.dist,c = e.cost;
            if(dist[to] > dist[temp] + d || (dist[to] == dist[temp] + d && len[to] > c)){
                dist[to] = dist[temp] + d;
                len[to] = c;
                if(!inque[to]){
                    inque[to] = true;
                    que.push(to);
                }
            }
        }
    }
    int ret = 0;
    for(int i = 1;i <= N;++i){
        ret += len[i];
    }
    return ret;
}

int main(){
    while(scanf("%d%d",&N,&M) == 2 && (N + M)){
        for(int i = 1;i <= N;++i) graph[i].clear();
        int u,v,d,c;
        for(int i = 0;i < M;++i){
            scanf("%d%d%d%d",&u,&v,&d,&c);
            graph[u].push_back(edge(v,d,c));
            graph[v].push_back(edge(u,d,c));
        }
        int ans = spfa(1);
        printf("%d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tiberius/p/9321534.html