# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
638927 | BackNoob | 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 <bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define endl '\n'
#define MASK(i) (1LL << (i))
#define ull unsigned long long
#define ld long double
#define pb push_back
#define all(x) (x).begin() , (x).end()
#define BIT(x , i) ((x >> (i)) & 1)
#define TASK "task"
#define sz(s) (int) (s).size()
using namespace std;
const int mxN = 2e5 + 227;
const int inf = 1e9 + 277;
const int mod = 1e9 + 7;
const ll infll = 1e18 + 7;
const int base = 307;
const int LOG = 20;
template <typename T1, typename T2> bool minimize(T1 &a, T2 b) {
if (a > b) {a = b; return true;} return false;
}
template <typename T1, typename T2> bool maximize(T1 &a, T2 b) {
if (a < b) {a = b; return true;} return false;
}
int n;
int k;
int res = inf;
int h[mxN][2];
int l[mxN];
int sub[mxN];
int dist[mxN];
int parcen[mxN];
int par[mxN][LOG + 1];
vector<int> node;
vector<pair<int, int>> adj[mxN];
ll rdist[mxN];
bool removed[mxN];
map<ll, int> mp;
void dfs(int u, int p)
{
for(auto it : adj[u]) {
int v = it.fi;
int c = it.se;
if(v == p) continue;
par[v][0] = u;
dfs(v, u);
}
}
void dfs_sz(int u, int p)
{
sub[u] = 1;
for(auto it : adj[u]) {
int v = it.fi;
int c = it.se;
if(v == p || removed[v] == true) continue;
dfs_sz(v, u);
sub[u] += sub[v];
}
}
int dfs_cen(int u, int p, int n)
{
for(auto it : adj[u]) {
int v = it.fi;
int c = it.se;
if(v == p || removed[v] == true) continue;
if(sub[u] > n / 2) return dfs_cen(v, u, n);
}
return u;
}
void find_best(int u, int p, int root)
{
node.pb(u);
for(auto it : adj[u]) {
int v = it.fi;
int c = it.se;
if(v == p) continue;
rdist[v] = rdist[u] + c;
dist[v] = dist[u] + 1;
if(rdist[v] == k) minimize(res, dist[v]);
if(k > rdist[v]) {
if(mp.count(k - rdist[v]) != 0) {
minimize(res, dist[v] + mp[k - rdist[v]]);
}
}
if(u == root) {
for(auto it : node) {
if(mp.count(dist[it]) == 0) mp[dist[it]] = rdist[it];
else minimize(mp[dist[it]], rdist[it]);
}
node.clear();
}
find_best(v, u, root);
}
}
void init_centroid(int u, int p)
{
parcen[u] = p;
dfs_sz(u, -1);
int c = dfs_cen(u, -1, sub[u]);
removed[c] = true;
node.clear();
mp.clear();
rdist[c] = 0;
dist[c] = 0;
find_best(c, -1, c);
removed[c] = true;
for(auto it : adj[c]) {
int v = it.fi;
if(removed[v] == false || v == p) init_centroid(v, u);
}
}
int best(int n, int k, int h[mxN][2], int l[mxN])
{
for(int i = 1; i < n; i++) {
int u = h[i][0];
int v = h[i][1];
++u;
++v;
adj[u].pb({v, l[i]});
adj[v].pb({u, l[i]});
}
dfs(1, -1);
//par[1][0] = 1;
//for(int j = 1; j <= LOG; j++)
//for(int i = 1; i <= n; i++) par[i][j] = par[par[i][j - 1]][j - 1];
init_centroid(1, -1);
if(res == inf) return -1;
return res;
}