이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
#define fastIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const int mxn = 2e5;
vector<vector<pair<int, int> > > adj(mxn+1, vector<pair<int, int> >());
int K;
int ans = 1e9;
bool processed[mxn+1];
int sz[mxn+1];
int lengths[mxn*5+1];
int getSize(int node, int p){
sz[node] = 1;
for(pair<int, int> tmp: adj[node]){
int to = tmp.first;
if(!processed[to] && to!=p) sz[node] += getSize(to, node);
}
return sz[node];
}
int getCentroid(int node, int p, int mxSize){
for(pair<int, int> tmp: adj[node]){
int to = tmp.first;
if(!processed[to] && to!=p && sz[to] > mxSize) return getCentroid(to, node, mxSize);
}
return node;
}
queue<pair<int, int> > q;
queue<int> l;
void dfs(int node, int p, int edgeLen, int edgeCnt){
if(K < edgeLen) return;
ans = min(ans, lengths[edgeLen-K] + edgeCnt);
q.push({edgeLen, edgeCnt});
l.push(edgeLen);
for(pair<int, int> tmp: adj[node]){
int to = tmp.first;
if(!processed[to] && to!=p) dfs(to, node, edgeLen + tmp.second, edgeCnt+1);
}
if(!p){
while(!q.empty()){
lengths[q.front().first] = min(lengths[q.front().first], q.front().second);
q.pop();
}
}
}
void centroidDecomposition(int node){
int centroid = getCentroid(node, 0, getSize(node, 0)/2);
processed[centroid] = 1;
lengths[0] = 0;
for(pair<int, int> tmp: adj[node]){
int to = tmp.first;
if(!processed[to]) dfs(node, 0, tmp.second, 1);
}
while(!l.empty()){
lengths[l.front()] = 1e9;
l.pop();
}
for(pair<int, int> tmp: adj[node]){
int to = tmp.first;
if(!processed[to]) centroidDecomposition(to);
}
}
int best_path(int n, int k, int h[][2], int l[]){
fastIO;
K = k;
memset(lengths, 0x3f, sizeof(lengths));
for(int i=0; i<n-1; i++){
adj[h[i][0]].push_back({h[i][1], l[i]});
adj[h[i][1]].push_back({h[i][0], l[i]});
}
centroidDecomposition(1);
return (ans == 1e9 ? -1 : ans);
}
# | 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... |