This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define pb push_back
#define F first
#define S second
#define sz(x) (int)x.size()
#define el "\n"
using namespace std;
typedef long long ll;
const int N = 2e5 + 500;
vector <pair <int, int> > g[N];
ll dp[N], cur, best, d[N];
vector <int> ans;
set <pair <ll, int> > se;
bool mk[N];
int n, k;
void dfs(int v, int pr) {
dp[v] = 0;
for (auto p : g[v]) {
int u = p.F, w = p.S;
if (u == pr || mk[u]) {
continue;
}
dfs(u, v);
dp[v] = max(dp[u] + w, dp[v]);
}
}
void go(int v, int pr, ll longest) {
multiset <ll> se;
for (auto u : g[v]) {
if (u.F == pr || mk[u.F]) {
continue;
}
se.insert(dp[u.F] + u.S);
}
if (max(longest, dp[v]) < cur) {
cur = max(longest, dp[v]);
best = v;
}
for (auto u : g[v]) {
if (u.F == pr || mk[u.F]) {
continue;
}
se.erase(se.find(dp[u.F] + u.S));
ll nlongest = longest;
if (sz(se)) {
nlongest = max(nlongest, *se.rbegin());
}
go(u.F, v, nlongest + u.S);
se.insert(dp[u.F] + u.S);
}
}
void add(int root, ll w) {
cur = 1e18;
dfs(root, -1);
go(root, -1, w);
se.insert({cur, best});
}
ll calc() {
for (int i = 1; i <= n; i++) {
d[i] = 1e18;
}
set <pair <ll, int> > se;
for (auto x : ans) {
d[x] = 0;
se.insert({0, x});
}
while (sz(se)) {
int v = se.begin() -> S;
se.erase(se.begin());
for (auto to : g[v]) {
int u = to.F, w = to.S;
if (d[u] > d[v] + w) {
d[u] = d[v] + w;
se.insert({d[u], u});
}
}
}
ll ret = 0;
for (int i = 1; i <= n; i++) {
ret = max(ret, d[i]);
}
return ret;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> k;
for (int i = 1; i < n; i++) {
int u, v, w;
cin >> u >> v >> w;
g[v].pb({u, w});
g[u].pb({v, w});
}
add(1, 0);
while (k > 0 && sz(se)) {
k--;
int del = se.rbegin() -> S;
se.erase(--se.end());
mk[del] = 1;
ans.pb(del);
for (auto to : g[del]) {
int u = to.F;
if (!mk[u]) {
add(u, to.S);
}
}
}
cout << calc() << el;
for (auto x : ans) {
cout << x << " ";
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |