#include <bits/stdc++.h>
#define pii pair<int,int>
#include "race.h"
using namespace std;
const int N=200005;
vector<pii>g[N];
map<int,int>*mp[N];
int dist[N],sz[N],dep[N];
int res=INT_MAX;
int k;
void dfs(int u,int prev){
sz[u]=1;
int mxsz=-1,mxn=-1;
for(auto el:g[u]){
int v=el.first;
int c=el.second;
if(v==prev)continue;
dist[v]=dist[u]+c;
dep[v]=dep[u]+1;
dfs(v,u);
sz[u]+=sz[v];
if(sz[v]>mxsz){
mxsz=sz[v];
mxn=v;
}
}
if(mxsz!=-1)mp[u]=mp[mxn];
else mp[u]=new map<int,int>();
if((*mp[u]).count(k-dist[u])){
int node=(*mp[u])[k-dist[u]];
res=min(res,abs(node-dep[u]));
}
(*mp[u])[dist[u]]=dep[u];
for(auto E:g[u]){
int v=E.first;
if(v==prev ||v==mxn)continue;
for(auto el:(*mp[v])){
int nx=el.first;
int de=el.second;
if((*mp[u]).count(k-nx)){
int node=(*mp[u])[k-nx];
res=min(res,abs(de-dep[u])+abs(dep[u]-node));
// cout<<"CHANGE"<<nx<<' '<<k<<' '<<de<<' '<<res<<'\n';
}
if((*mp[u]).count(nx)){
(*mp[u])[nx]=min((*mp[u])[nx],de);
}else (*mp[u])[nx]=de;
}
}
/*
cout<<"NODE";
cout<<u<<' '<<prev<<' '<<dist[u]<<' '<<dep[u]<<'\n';
for(auto el:(*mp[u]))cout<<el.first<<' '<<el.second<<'\n';
*/
}
int best_path(int N, int K, int H[][2], int L[])
{
k=K;
for(int i=0;i<N-1;i++){
int u,v,c;u=H[i][0];
v=H[i][1];
c=L[i];
g[u].push_back({v,c});
g[v].push_back({u,c});
}
dep[1]=0;
dfs(1,N);
if(res!=INT_MAX)return res;
else return -1;
}
/*
int main(){
int n=4;
int k=7;
int h[][2]={{0,1},{1,2},{1,3}};
int l[]={1,2,4};
std::cout<<best_path(n,k,h,l)<<'\n';
}
*/
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
6 ms |
4984 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
6 ms |
4984 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
6 ms |
4984 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
6 ms |
4984 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |