#include <bits/stdc++.h>
using namespace std;
const int kMaxN = 5e4 + 5;
struct Edge {
int from;
int to;
int nxt;
long long w;
} e[kMaxN * 2];
int tot, head[kMaxN];
void Add(int x, int y, long long w) {
e[++tot] = (Edge){x, y, head[x], w};
head[x] = tot;
}
int n, m;
int ans;
multiset<long long> s[kMaxN];
void Dfs(int x, int f, long long k, long long w) {
s[x].clear();
for (int i = head[x]; i; i = e[i].nxt) {
int to = e[i].to;
if (to == f) {
continue;
}
Dfs(to, x, k, e[i].w);
}
long long p = 0;
multiset<long long>::iterator it = s[x].lower_bound(k);
multiset<long long>::iterator ed = s[x].end();
while (ed != it) {
ed--;
ans++;
s[x].erase(ed);
}
while (!s[x].empty()) {
if (s[x].size() == 1) {
p = max(p, *s[x].begin());
s[x].erase(s[x].begin());
break;
}
multiset<long long>::iterator pos = s[x].lower_bound(k - *s[x].begin());
if (pos == s[x].begin()) {
pos++;
}
if (pos == s[x].end()) {
p = max(p, *s[x].begin());
s[x].erase(s[x].begin());
continue;
}
ans++;
s[x].erase(s[x].begin());
s[x].erase(pos);
}
s[f].insert(p + w);
}
bool Check(long long x) {
ans = 0;
Dfs(1, 0, x, 0);
return ans >= m;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n - 1; i++) {
int x, y;
long long w;
scanf("%d%d%lld", &x, &y, &w);
Add(x, y, w);
Add(y, x, w);
}
long long l = 0, r = 1e11;
while (l + 1 < r) {
long long mid = (l + r) / 2;
if (Check(mid)) {
l = mid;
}
else {
r = mid;
}
}
if (Check(l + 1)) {
l++;
}
printf("%lld\n", l);
return 0;
}
Rt
下载了数据在本机 (windows−devc++)过了,但是在洛谷就 RE 了,求大神解释...