1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <iostream> #include <algorithm> #include <vector> #define maxn 200010 #define ll long long using namespace std;
int n, k, a[maxn];
struct Edge { int to, next, w; } e[maxn * 2]; int c1, head[maxn]; inline void add_edge(int u, int v) { e[c1].to = v; e[c1].next = head[u]; head[u] = c1++; }
int son[maxn]; ll mxd[maxn], dep[maxn]; void dfs(int u, int fa) { for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to; if (v == fa) continue; mxd[v] = dep[v] = dep[u] + a[v]; dfs(v, u); if (mxd[v] > mxd[u]) mxd[u] = mxd[v], son[u] = v; } }
int top[maxn]; void dfs(int u, int fa, int topf) { top[u] = topf; if (son[u]) dfs(son[u], u, topf); for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to; if (v == fa || v == son[u]) continue; dfs(v, u, v); } }
int main() { fill(head, head + maxn, -1); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> k; for (int i = 1; i <= n; ++i) cin >> a[i]; for (int i = 1; i < n; ++i) { int x, y, z; cin >> x >> y; add_edge(x, y); add_edge(y, x); } dep[1] = mxd[1] = a[1]; dfs(1, 0); dfs(1, 0, 1); vector<ll> A; for (int i = 1; i <= n; ++i) if (top[i] == i) A.push_back(mxd[i] - dep[i] + a[i]); sort(A.begin(), A.end(), greater<ll>()); ll ans = 0; for (int i = 0; i < min(k, (int) A.size()); ++i) ans += A[i]; cout << ans << "\n"; return 0; }
|