#include "race.h"
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define sc second
#define pii pair<int,int>
using namespace std;
const int MAXN = 2e5+5;
const int mod7 = 1e9+7;
const long long inf = 1e18;
int n,k;
long long rez = inf;
vector<vector<pii>> graf(MAXN);
int nmnodes[MAXN];
bool wasCentroid[MAXN];
unordered_map<int,int> sviputevi;
vector<pii> trsumsonpath;
int dfs(int nod, int p)
{
nmnodes[nod] = 1;
for(auto x: graf[nod])
{
if(x.fi==p || wasCentroid[x.fi])continue;
nmnodes[nod] += dfs(x.fi,nod);
}
return nmnodes[nod];
}
void dfs2(int nod, int p, int d, int s)
{
trsumsonpath.pb({s,d});
for(auto x:graf[nod])
{
if(x.fi==p || wasCentroid[x.fi])continue;
dfs2(x.fi, nod, d+1, s+x.sc);
}
}
int findCentroid(int nod, int treesize, int p)
{
for(auto x: graf[nod])
{
if(x.fi == p || wasCentroid[x.fi])continue;
if(nmnodes[x.fi]*2 > treesize)return findCentroid(x.fi,treesize,nod);
}
return nod;
}
void solve(int nod)
{
int treesize = dfs(nod,nod);
int centroid = findCentroid(nod, treesize, nod);
wasCentroid[centroid] = 1;
sviputevi.clear();
sviputevi[0] = 0;
for(auto x: graf[centroid])
{
if(wasCentroid[x.fi])continue;
trsumsonpath.clear();
dfs2(x.fi, x.fi, 1,x.sc);
//for(auto y: trsumsonpath)cout << y.fi << " " << y.sc;cout << endl;
for(auto y:trsumsonpath)
{
if(k-y.fi >= 0 && sviputevi.count(k-y.fi))
{
rez = min(rez, 0ll+y.sc + sviputevi[k-y.fi]);
}
}
for(auto y:trsumsonpath)
{
if(k-y.fi >= 0)
{
if(sviputevi.count(y.fi))sviputevi[k-y.fi] = min(0ll+sviputevi[k-y.fi], 0ll+y.sc);
else sviputevi[y.fi] =y.sc;
}
}
//for(auto y:sviputevi)cout << y.fi << " " << y.sc << endl;
}
for(auto x: graf[centroid])
{
if(wasCentroid[x.fi])continue;
solve(x.fi);
}
}
int best_path(int N, int K, int H[][2], int L[])
{
n = N;
k = K;
for(int i=0; i<n; i++)
{
graf[H[i][0]].pb(mp(H[i][1], L[i]));
graf[H[i][1]].pb(mp(H[i][0], L[i]));
}
solve(0);
if(rez == inf)return -1;
return rez;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
9052 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
9052 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
9052 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
2 ms |
9052 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |