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>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pll;
typedef pair<int,int> pii;
typedef pair <int,pii> piii;
#define forr(_a,_b,_c) for(_a = (_b); _a <= (_c); ++_a)
#define ford(_a,_b,_c) for(_a = (_b) + 1; _a --> (_c);)
#define forf(_a,_b,_c) for(_a = (_b); _a < (_c); ++_a)
#define st first
#define nd second
#define pb push_back
#define mp make_pair
#define all(x) begin(x),end(x)
#define mask(i) (1LL << (i))
#define bit(x, i) (((x) >> (i)) & 1)
#define bp __builtin_popcountll
#define file "test"
const int Nn = 5e5 + 5;
const int oo = 1e9;
const ll mod = 1e9 + 7;
vector <pii> a[Nn];
int sz[Nn], del[Nn], ans, k, par[Nn];
map <int, int> m;
int dfs (int u, int p){
sz[u] = 1;
for (pii t : a[u]){
int v = t.st;
if (v != p && !del[v])
sz[u] += dfs(v, u);
}
return sz[u];
}
int get (int u, int p, int nsz){
for (pii t : a[u]){
int v = t.st;
if (v != p && !del[v] && sz[v] * 2 > nsz)
return get(v, u, nsz);
}
return u;
}
void calc (int u, int p, int dep, int dis, bool keep){
if (dis > k) return;
if (!keep)
ans = min (ans, dep - m[k - dis] + oo);
else m[dis] = max (m[dis], oo - dep);
for (pii t : a[u]){
int v = t.st, w = t.nd;
if (v != p && !del[v])
calc(v, u, dep + 1, dis + w, keep);
}
}
// m[i] = oo - dep[i];
void build (int u, int p){
int ct = get(u, u, dfs(u, u));
par[ct] = p;
del[ct] = 1;
m.clear();
m[0] = oo;
for (pii t : a[ct]){
int v = t.st, w = t.nd;
if (!del[v]){
calc(v, u, 1, w, 0);
calc(v, u, 1, w, 1);
}
}
for (pii t : a[ct]){
int v = t.st;
if (!del[v]){
build(v, ct);
}
}
}
int i, n, u, v, w;
int best_path (int nn, int kk, int edge[][2], int ww[]){
ans = oo;
n = nn;
k = kk;
if (k == 1)
return 0;
forf (i,0,n - 1){
u = edge[i][0];
v = edge[i][1];
w = ww[i];
a[u].pb({v,w});
a[v].pb({u,w});
}
build(0, -1);
return (ans <= n - 1 ? ans : -1);
}
/*
*/
# | 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... |