이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#define s second
#define f first
#define pb push_back
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
typedef vector<int> vi;
#define FOR(i, a, b) for (ll i = (a); i<b; i++)
const int MN = 3e5 + 10;
vpii adj[MN];
int d[MN]; // from root in highways
int d2[MN]; // from root in distance
int k;
void dfs(int cur = 0, int dist = 0, int dist2 = 0, int p = -1) {
// cout << cur << endl;
d[cur]=dist;
d2[cur]=dist2;
for (auto val: adj[cur]) {
if (val.f != p) {
dfs(val.f, dist + 1, dist2 + val.s, cur);
}
}
}
map<int, int> small[MN];
int ans = 1e9;
void solve(int cur, int p=-1) {
for (auto val: adj[cur]) {
if (val.f != p) {
solve(val.f, cur);
// cout << ' ' << val.f << ' ' << cur << d2[cur] << endl;
if (small[val.f].find(k + d2[cur]) != small[val.f].end()) {
// cout << " " << small[val.f][k + d2[cur]] << d[cur] << endl;
ans = min(ans, small[val.f][k + d2[cur]] - d[cur]);
// cout << ans << endl;
}
if (small[val.f].size() > small[cur].size()) swap(small[val.f], small[cur]);
// merge
for (pii nx: small[val.f]) {
if (small[cur].find(k + 2*d2[cur] - nx.f) != small[cur].end()) {
ans = min(ans, small[cur][k + 2*d2[cur] - nx.f] + nx.s - d[cur]);
}
}
for (pii nx: small[val.f]) {
if (small[cur].find(nx.f) == small[cur].end()) small[cur][nx.f]=nx.s;
else small[cur][nx.f]=min(small[cur][nx.f], nx.s);
}
}
}
if (small[cur].find(d2[cur]) == small[cur].end()) small[cur][d2[cur]]=d[cur];
else small[cur][d2[cur]]=min(small[cur][d2[cur]], d[cur]);
// cout << cur << endl;
// for (auto val: small[cur]) {
// cout << val.f << val.s << endl;
// }
}
int best_path(int N, int K, int H[][2], int L[])
{
k = K;
FOR(i, 0, N-1) {
adj[H[i][0]].pb({H[i][1], L[i]});
}
dfs();
solve(0);
if (ans == 1e9) ans = -1;
return ans;
}
# | 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... |