P2916 [USACO08NOV]安慰奶牛Cheering up the Cow

就是建一个树,然后从某根开始走,每走一条边就要消耗两边点权+边的边权。最后再加上一个根的点权

直接改变边权然后跑最小生成树就好了。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<cstring>
using namespace std;
int n, p;
int ans = 1<<30;
int a[10005];
int fa[10005];
struct edge {
    int s, e, l;
} e[100005];
int cmp(const edge &a, const edge &b) {
    return a.l < b.l;
}
int find(int x) {
    return fa[x] == x?x:fa[x] = find(fa[x]);
}
int main() {
    scanf("%d %d", &n, &p);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
        ans = min(ans,a[i]);
        fa[i] = i;
    }
    for(int i = 1; i <= p; i++) {
        scanf("%d %d %d", &e[i].s, &e[i].e, &e[i].l);
        e[i].l *= 2;
        e[i].l += a[e[i].s] + a[e[i].e];
    }
    sort(e + 1,e + p + 1,cmp);
    for(int i = 1; i <= p; i++) {
        int x = find(e[i].s), y = find(e[i].e);
        if(x != y) {
            ans += e[i].l;
            fa[x] = y;
        }
    }
    printf("%d", ans);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/jiqimin/p/10945048.html