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;
#define OPTM ios_base::sync_with_stdio(0); cin.tie(0);
#define INF int(1e9+7)
#define ln '\n'
#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define us unsigned short
#define FOR(i,s,n) for (int i = s; i < n; i++)
#define FORR(i,n,s) for (int i = n; i > s; i--)
#define FORX(u, arr) for (auto u : arr)
#define PB push_back
#define in(v,x) (v.find(x) != v.end())
#define F first
#define S second
#define PII pair<int, int>
#define PLL pair<ll, ll>
#define UM unordered_map
#define US unordered_set
#define PQ priority_queue
#define ALL(v) v.begin(), v.end()
const ll LLINF = 1e18+1;
#define int long long
struct Edge {
int F,w;
};
const int MAXN = 2e5+1, LOG = 19;
int n,k;
US<int> v[MAXN];
vector<PII> v1[MAXN], add;
int dist[MAXN], len[MAXN], sz[MAXN];
UM<int,int> mp;
bool z[MAXN];
int res = LLINF;
int find_centroid(int s, int pa, int num) {
FORX(u,v[s]) {
if (u == pa || z[u]) continue;
if (sz[u] > num/2) return find_centroid(u,s,num);
}
return s;
}
void dfs(int s, int pa) {
sz[s] = 1;
FORX(u,v[s]) {
if (u == pa || z[u]) continue;
dfs(u,s);
sz[s] += sz[u];
}
}
void dfs1(int s, int pa, int src, int l, int d) {
FORX(u,v1[s]) {
if (u.F == pa || z[u.F]) continue;
int nl = l+u.S, nd = d+1LL;
if (nl > k) continue;
if (nl == k) res = min(res, nd);
else if (nl < k && mp.count(k-nl)) res = min(res, nd+mp[k-nl]);
add.PB({nl,nd});
dfs1(u.F,s,src,nl,nd);
if (s == src) {
FORX(y,add) {
int l1 = y.F, d1 = y.S;
if (!mp.count(l1)) mp[l1] = d1;
else mp[l1] = min(mp[l1],d1);
}
add.clear();
}
}
}
void decomp(int s, int pa) {
mp.clear();
dfs(s,pa);
int c = find_centroid(s,pa,sz[s]);
dfs1(c,-1,c,0LL,0LL);
z[c] = 1;
FORX(u,v[c]) if (u != pa && !z[u]) decomp(u,c);
}
int32_t best_path(int32_t N, int32_t K, int32_t H[][2], int32_t L[]) {
OPTM;
n = N; k = K;
FOR(i,0,n-1) {
v1[H[i][0]].PB({H[i][1],L[i]});
v1[H[i][1]].PB({H[i][0],L[i]});
v[H[i][0]].insert(H[i][1]);
v[H[i][1]].insert(H[i][0]);
}
decomp(0,-1);
return res == LLINF ? -1 : res;
}
# | 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... |