# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1046191 | I_FloPPed21 | 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>
using namespace std;
map<int,long long> mp[200005] ;
vector<pair<int,int>> adj[200005];
long long h[200005][2], v[200005],target = 0,sum[200005],height[200005],ans = 1e9,n,k;
void precomp(int nod, int p, int hd)
{
height[nod] = hd ;
for ( auto u : adj[nod] )
{
if ( u.first != p )
{
sum[u.first] += sum[nod] + u.second;
precomp(u.first,nod,hd + 1);
}
}
}
void small(int nod,int p )
{
int real_target = target + 2 * sum[nod];
for ( auto u : adj[nod] )
{
if ( u.first != p )
{
small(u.first,nod);
}
}
for ( auto u : adj[nod] )
{
if( u.first != p )
{
if( mp[u.first].size() > mp[nod].size())
swap(mp[nod],mp[u.first]);
for ( auto k : mp[u.first] )
{
long long real = real_target - k.first ;
/* if( nod == 6 && u.first == 8 )
{
cout << real << '\n';
}*/
if ( mp[nod][real] != 0 )
{
//cout << nod << " " << u.first << " " << k.first << " " << k.second << '\n';
ans = min ( long(ans), long(k.second + mp[nod][real] - 2 * height[nod]));
}
if( mp[nod][k.first] == 0 )
mp[nod][k.first] = k .second;
else
mp[nod][k.first] = min(mp[nod][k.first],k.second);
}
}
}
/*if( nod == 6)
{
cout << mp[nod][real_target]<< '\n';
}*/
if( mp[nod][sum[nod]] == 0 )
mp[nod][sum[nod]] = 1e11;
mp[nod][sum[nod]] = min(height[nod],mp[nod][sum[nod]]);
if( mp[nod][real_target-sum[nod]] != 0 )
ans = min ( ans,mp[nod][real_target-sum[nod]] - height[nod]);
}
int best_path(int n, int k, int h[][2], int costs [] )
{
target =k ;
for ( int i = 1; i < n ; i ++ )
{
adj[h[i][1]].push_back({h[i][0],v[i]});
adj[h[i][0]].push_back({h[i][1],v[i]});
}
for ( int i = 1; i < n ; i ++)
v[i] =costs[i];
precomp(0,-1,1);
small(0,-1);
if( mp[0][k] != 0 )
ans = min ( ans, mp[0][k]);
if( ans == 1e9)
return -1;
else
return ans ;
}
/*int main()
{
cin >> n >> k;
for ( int i = 1; i < n ; i ++ )
{
cin >> h[i][0] >> h[i][1] >> v[i] ;
}
cout << best_path(n,k,h,v);
return 0;
}