# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
888513 | dwuy | Race (IOI11_race) | C++14 | 0 ms | 0 KiB |
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>
#define int long long
#define fi first
#define se second
using namespace std;
typedef pair<int, int> pii;
const int MX = 200005;
int n, k, ans = MX;
int numC[MX];
bitset<MX> vist;
vector<pii> G[MX];
void calChild(int u, int p){
numC[u] = 1;
for(pii &tmp: G[u]){
int v, c;
tie(v, c) = tmp;
if(v==p || vist[v]) continue;
calChild(v, u);
numC[u] += numC[v];
}
}
int Centroid(int u, int p, const int &half){
for(pii &tmp: G[u]){
int v = tmp.fi;
if(v == p || vist[v]) continue;
if(numC[v] > half) return Centroid(v, u, half);
}
return u;
}
int dis[MX];
int node[MX];
int getmap(unordered_map<int, int> &mp, int value){
auto itr = mp.find(value);
if(itr == mp.end()) return 0;
return itr->se;
}
int calValue(int u){
unordered_map<int, int> mp;
int res = MX;
mp[0] = 1;
for(pii &tmp: G[u]){
int v, c;
tie(v, c) = tmp;
vector<int> path;
path.push_back(c);
stack<pii> Q;
Q.push({v, u});
node[v] = 2;
dis[v] = c;
while(Q.size()){
int u, p;
tie(u, p) = Q.top();
Q.pop();
path.push_back(u);
for(pii &tmp: G[u]){
int v, c;
tie(v, c) = tmp;
if(vist[v] || v == p) continue;
Q.push({v, u});
dis[v] = dis[u] + c;
node[v] = node[u] + 1;
}
}
for(int vt: path) if(dis[vt]<=k){
int gm = getmap(mp, k - dis[vt]);
if(gm) res = min(res, gm + node[vt] - 1);
mp[dis[vt]] = min(mp[dis[vt]], node[vt]);
}
}
return res;
}
void dwuy_simp_nvpu(int u){
calChild(u, 0);
u = Centroid(u, 0, numC[u]>>1);
ans = min(ans, calValue(u));
vist[u] = 1;
for(pii &tmp: G[u]){
int v = tmp.fi;
if(!vist[v]) dwuy_simp_nvpu(v);
}
}
int best_path(int n, int k, int H[][2], int L[]){
::n = n;
::k = k;
for(int i=0; i<n; i++){
int u = H[i][0];
int v = H[i][1];
int c = L[i];
u++, v++;
G[u].push_back({v, c});
G[v].push_back({u, c});
}
dwuy_simp_nvpu(1);
return ans==MX? -1 : ans - 1;
}
/**
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
/// huhuhu nho pu qua
int n, k;
cin >> n >> k;
int h[n-1][2], l[n-1];
for(int i=0; i<n-1; i++){
cin >> h[i][0] >> h[i][1] >> l[i];
}
cout << best_path(n, k, h, l);
return 0;
}
**/
/**
4 3
0 1 1
1 2 2
1 3 4
3 3
0 1 1
1 2 1
11 12
0 1 3
0 2 4
2 3 5
3 4 4
4 5 6
0 6 3
6 7 2
6 8 5
8 9 6
8 10 7
**/