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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
| // 42jerrykim.github.io에서 더 많은 정보를 확인 할 수 있습니다.
#include <bits/stdc++.h>
using namespace std;
struct Pair { long long profit; int cnt; };
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k; if (!(cin >> n >> k)) return 0;
vector<vector<pair<int,long long>>> g(n+1);
for (int i = 0; i < n-1; ++i) {
int u, v; long long c; cin >> u >> v >> c;
g[u].push_back({v, c}); g[v].push_back({u, c});
}
// Rooting and order
vector<int> parent(n+1, 0), order; order.reserve(n);
vector<int> st; st.reserve(n); parent[1] = -1; st.push_back(1);
while (!st.empty()) {
int u = st.back(); st.pop_back(); order.push_back(u);
for (auto &e : g[u]) {
int v = e.first; if (v == parent[u]) continue;
if (parent[v] != 0) continue; parent[v] = u; st.push_back(v);
}
}
vector<long long> dpA(n+1, 0), dpB(n+1, 0);
vector<int> cntA(n+1, 0), cntB(n+1, 0);
auto better = [](const Pair &a, const Pair &b) {
if (a.profit != b.profit) return a.profit > b.profit;
return a.cnt > b.cnt; // tie-break: prefer larger count
};
auto run = [&](long long lambda) -> Pair {
for (int idx = (int)order.size() - 1; idx >= 0; --idx) {
int u = order[idx];
long long baseProfit = 0; int baseCnt = 0;
for (auto &e : g[u]) {
int v = e.first; if (v == parent[u]) continue;
baseProfit += dpA[v]; baseCnt += cntA[v];
}
Pair bestDelta{0, 0};
for (auto &e : g[u]) {
int v = e.first; if (v == parent[u]) continue; long long w = e.second;
long long deltaProfit = dpB[v] + (w - lambda) - dpA[v];
int deltaCnt = cntB[v] + 1 - cntA[v];
Pair cand{deltaProfit, deltaCnt};
if (better(cand, bestDelta)) bestDelta = cand;
}
// u matched with parent → cannot match children
dpB[u] = baseProfit; cntB[u] = baseCnt;
// u free → at most one child match
dpA[u] = baseProfit + bestDelta.profit; cntA[u] = baseCnt + bestDelta.cnt;
}
return {dpA[1], cntA[1]};
};
const long long LAM_INF = 1000000000000LL; // 1e12
Pair neg = run(-LAM_INF);
if (neg.cnt < k) { cout << "Impossible\n"; return 0; }
long long lo = -LAM_INF, hi = LAM_INF;
while (lo < hi) {
long long mid = (lo + hi) >> 1;
Pair res = run(mid);
if (res.cnt <= k) hi = mid; else lo = mid + 1;
}
long long lam = lo;
// convex dual reconstruction
Pair r1 = run(lam); long long ans1 = r1.profit + lam * 1LL * k;
Pair r0 = run(lam - 1); long long ans0 = r0.profit + (lam - 1) * 1LL * k;
long long ans = min(ans0, ans1);
cout << ans << '\n';
return 0;
}
|