이 제출은 이전 버전의 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];
vector<int> lengths(mxn*5+1, 1e9);
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[K-edgeLen] + 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[centroid]){
int to = tmp.first;
if(!processed[to]) dfs(to, 0, tmp.second, 1);
}
while(!L.empty()){
lengths[L.front()] = 1e9;
L.pop();
}
for(pair<int, int> tmp: adj[centroid]){
int to = tmp.first;
if(!processed[to]) centroidDecomposition(to);
}
}
int best_path(int n, int k, int h[][2], int l[]){
fastIO;
K = k;
for(int i=0; i<n-1; i++){
h[i][0]++; h[i][1]++;
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);
}
// int main(){
// int n, k;
// cin >> n >> k;
// int h[n-1][2], l[n-1];
// for(int i=0; i<n-1; i++){
// cin >> h[i][0] >> h[i][1];
// }
// for(int i=0; i<n-1; i++){
// cin >> l[i];
// }
// cout << best_path(n, k, h, l) << '\n';
// }
# | 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... |