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 "race.h"
#include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define ll long long
#define ld long double
#define ar array
const int INF = 1e9;
const int MOD = 1e9 + 7;
const int MXN = 2e5+9, MXK = 1e6+9;
vector<ar<int,2>> g[MXN];
vector<int> length(MXK, INF), lastcnt(MXK, -1);
vector<bool> dead(MXK, false);
int n, k, ans = INT_MAX, cnt = 0;
int OneCentroid(int rt) {
vector<int> sz(n);
function<void(int,int)> get_sz = [&](int u, int pu) {
sz[u] = 1;
for (auto v : g[u]) if (v[1] != pu && !dead[v[1]]) {
get_sz(v[1], u);
sz[u] += sz[v[1]];
}
};
get_sz(rt, rt);
function<int(int,int)> cent = [&](int u, int pu) {
for (auto v : g[u]) if (v[1] != pu && !dead[v[1]]) {
if (sz[v[1]] > sz[rt]/2) return cent(v[1], u);
}
return u;
};
return cent(rt, rt);
}
void dfs(int u, int pu, int len, int dist, bool update) {
if (k < dist || len > ans) return;
if (!update && k-dist >= 0 && lastcnt[k-dist] == cnt)
ans = min(ans, length[k-dist] + len);
if (update && (lastcnt[dist] < cnt || len < length[dist]))
length[dist] = len, lastcnt[dist] = cnt;
for (auto v : g[u]) if (v[1] != pu && !dead[v[1]])
dfs(v[1], u, len + 1, dist + v[0], update);
}
void decompose(int start) {
int cen = OneCentroid(start);
length[0] = 0; lastcnt[0] = ++cnt;
// get length, distance to each node in subtree of centroid from centroid
// ans = min(ans, length) if distance corresponding to it is k
for (auto v : g[cen]) if (!dead[v[1]]) {
dfs(v[1], cen, 1, v[0], false);
dfs(v[1], cen, 1, v[0], true);
}
dead[cen] = true;
for (auto v : g[cen]) if (!dead[v[1]]) { decompose(v[1]); }
dead[cen] = false;
}
int best_path(int N, int K, int H[][2], int L[]) {
n = N, k = K;
for (int i = 0; i < N-1; i++) {
g[H[i][0]].push_back({L[i], H[i][1]});
g[H[i][1]].push_back({L[i], H[i][0]});
}
decompose(0);
return (ans < INF/2) ? ans : -1;
}
Compilation message (stderr)
race.cpp:5: warning: ignoring #pragma comment [-Wunknown-pragmas]
5 | #pragma comment(linker, "/stack:200000000")
|
# | 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... |