bzoj3252: 攻略(贪心)


/*
因为权值都是正的, 所以贪心的正确性能保证
然后重链贪心跑一下就好了

*/
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<iostream>
#define ll long long
#define M 200010
#define mmp make_pair
using namespace std;
int read() {
    int nm = 0, f = 1;
    char c = getchar();
    for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
    for(; isdigit(c); c = getchar()) nm = nm * 10 + c - '0';
    return nm * f;
}
vector<int> to[M];
ll ver[M], sta[M], tp, top[M], son[M], n, k;

void dfs(int now, int fa) {
    for(int i = 0; i < to[now].size(); i++) {
        int vj = to[now][i];
        if(vj == fa) continue;
        dfs(vj, now);
        if(ver[vj] > ver[son[now]]) son[now] = vj;
    }
    ver[now] += ver[son[now]];
}

void dfss(int now, int fa) {
    if(top[now] == now) sta[++tp] = ver[now];
    if(son[now]) {
        top[son[now]] = top[now];
        dfss(son[now], now);
    }
    for(int i = 0; i < to[now].size(); i++) {
        int vj = to[now][i];
        if(vj == fa || vj == son[now]) continue;
        top[vj] = vj;
        dfss(vj, now);
    }
}

int main() {
    n = read(), k = read();
    for(int i = 1; i <= n; i++) ver[i] = read();
    for(int i = 1; i < n; i++) {
        int vi = read(), vj = read();
        to[vi].push_back(vj);
        to[vj].push_back(vi);
    }
    dfs(1, 1);
    top[1] = 1;
    dfss(1, 1);
    sort(sta + 1, sta + tp + 1, greater<ll>() );
    ll ans = 0;
    for(int i = 1; i <= k; i++) ans += sta[i];
    cout << ans << "\n";
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/luoyibujue/p/10686091.html
今日推荐