# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
486991 | noob_c0de | Race (IOI11_race) | C++17 | 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>
using namespace std;
#define int long long
#define ar array
#define db double
#define sz(x) (int)x.size()
#define mat vector<vector<int> >
const db pi = acos(-1);
const int mxn = 2e5 + 7, INF = 1e6 + 7;;
int n, k, ans;
vector<ar<int, 2> > g[mxn];
int depth[mxn], len[mxn];
map<int, int> mp[mxn];
int r[mxn];
// int h[mxn][2];
// int l[mxn];
void dfs(int u, int p)
{
for (auto [v, w] : g[u])
{
if (v == p) continue;
depth[v] = depth[u] + 1;
len[v] = len[u] + w;
dfs(v, u);
}
}
void gopset(int u, int v)
{
if (sz(mp[r[u]]) < sz(mp[r[v]])) swap(r[u], r[v]);
for (auto it = mp[r[v]].begin(); it != mp[r[v]].end(); it++)
{
int t = it->first, dep = it->second;
if (mp[r[u]].count(k - t + 2 * len[u]))
{
ans = min(ans, mp[r[u]][k - t + 2 * len[u]] + dep - 2 * depth[u]);
}
}
for (auto it = mp[r[v]].begin(); it != mp[r[v]].end(); it++)
{
int t = it->first, dep = it->second;
if (mp[r[u]].count(t)) mp[r[u]][t] = min(mp[r[u]][t], dep);
else mp[r[u]][t] = dep;
}
}
void dfs2(int u, int p)
{
mp[u][len[u]] = depth[u];
for (auto [v, w] : g[u])
{
if (v == p) continue;
dfs2(v, u);
gopset(u, v);
}
}
int best_path(int n, int k, int h[][2], int l[])
{
for (int i = 0; i < n; i++)
{
g[h[i][0]].push_back({h[i][1], l[i]});
g[h[i][1]].push_back({h[i][0], l[i]});
}
for (int i = 0; i < n; i++) r[i] = i;
dfs(0, 0);
ans = INF;
dfs2(0, 0);
if (ans == INF) return -1;
return ans;
}
// signed main()
// {
// ios::sync_with_stdio(0);
// cin.tie(0); cout.tie(0);
// // De nghi ko bat ultra instinct tay nhanh hon nao luc lam bai
// cin >> n >> k;
// for (int i = 0; i < n - 1; i++) cin >> h[i][0] >> h[i][1];
// for (int i = 0; i < n - 1; i++) cin >> l[i];
// int res = best_path(n, k, h, l);
// if (res == INF) cout << -1;
// else cout << res;
// return 0;
// }