#include <bits/stdc++.h>
using namespace std;
#define ll long long
vector<vector<pair<ll, ll>>> grafo;
void dfs2(ll src, ll parent, ll currPathTam, ll currPathArestas);
vector<ll> subtrees;
vector<bool> visited;
void calc_subtrees(ll src, ll parent){
subtrees[src] = 1;
for (auto& vz: grafo[src]){
if (visited[vz.first] || vz.first == parent) continue;
calc_subtrees(vz.first, src);
subtrees[src] += subtrees[vz.first];
}
}
ll centroid(ll src, ll parent, ll subTreeSize){
for (auto vz: grafo[src]){
if (parent == vz.first) continue;
if (subtrees[vz.first] > subTreeSize/2){
if (visited[vz.first]) continue;
return centroid(vz.first, src, subTreeSize);
}
}
return src;
}
ll find_centroid(ll beg, ll parent){
subtrees.assign(grafo.size(), 0);
calc_subtrees(beg, parent);
return centroid(beg, -1, subtrees[beg]);
}
ll minCam = INT_MAX;
unordered_map<ll, ll> melhor; // melhor caminho que chega naquela raiz com tamanho sendo a chave e o número de arestas sendo o valor
void dfs1(ll src, ll parent, ll currPathTam, ll currPathArestas, ll K){
if (melhor.find(K - currPathTam) != melhor.end())
minCam = min(minCam, currPathArestas + melhor[K - currPathTam]);
for (int i = 0; i< grafo[src].size() ; i++){
auto [vz, w] = grafo[src][i];
if (parent == vz) continue;
dfs1(vz, src, currPathTam + w, currPathArestas + 1, K);
}
}
void dfs2(ll src, ll parent, ll currPathTam, ll currPathArestas){
if (melhor.find(currPathTam)!= melhor.end())
melhor[currPathTam ] = min(melhor[currPathTam], currPathArestas);
else
melhor[currPathTam] = currPathArestas;
for (auto &[vz, w]: grafo[src]){
if (vz == parent) continue;
dfs2(vz, src, currPathTam + w, currPathArestas + 1);
}
}
void solve(ll start, ll K){
ll cntd = find_centroid(start, -1);
visited[cntd] = true;
melhor.clear();
for (auto [v, w] : grafo[cntd]){
if (visited[v] ) continue;
dfs1(v, cntd, w, 1, K);
dfs2(v, cntd, w, 1);
}
for (auto [v, w] : grafo[cntd]){
if (!visited[v]){
solve(v, K);
}
}
}
int best_path(int N, int K, int H[][2], int L[])
{
minCam = INT_MAX;
visited.assign(N, false);
subtrees.assign(N, 0);
grafo.resize(N);
for (int i = 0; i < N - 1; i++)
{
grafo[H[i][0]].push_back({H[i][1], L[i]});
grafo[H[i][1]].push_back({H[i][0], L[i]});
}
solve(0,K);
return (minCam == INT_MAX ? -1 : minCam);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |