이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
#define fr first
#define sc second
typedef long long ll;
const int MAX = 2e6 + 15;
const int INF = 0x3f3f3f3f;
int n, k, ans, sub[MAX], f[MAX];
vector<pair<int, int>> adj[MAX], update;
vector<int> fixupdate;
bool removed[MAX];
void dfsInit(int u, int p){
sub[u] = 1;
for(auto e : adj[u]){
int v = e.fr;
if(v == p || removed[v]) continue;
dfsInit(v, u);
sub[u] += sub[v];
}
}
int findCentroid(int u, int p, int sz){
for(auto e : adj[u]){
if(e.fr == p || removed[e.fr]) continue;
if(sub[e.fr] > sz / 2)
return findCentroid(e.fr, u, sz);
}
return u;
}
void dfsCalc(int u, int p, int edges, int length){
update.emplace_back(length, edges);
fixupdate.emplace_back(length);
for(auto e : adj[u]){
int v = e.fr, w = e.sc;
if(v == p || removed[v]) continue;
dfsCalc(v, u, edges + 1, length + w);
}
}
void decompose(int u){
dfsInit(u, -1);
int centroid = findCentroid(u, -1, sub[u]);
removed[centroid] = true;
f[0] = 0;
for(auto e : adj[centroid]){
if(removed[e.fr]) continue;
dfsCalc(e.fr, -1, 1, e.sc);
for(auto p : update)
if(p.fr <= k) ans = min(ans, p.sc + f[k - p.fr]);
for(auto p : update)
f[p.fr] = min(f[p.fr], p.sc);
update.clear();
}
for(auto x : fixupdate) f[x] = INF;
fixupdate.clear();
for(auto e : adj[centroid])
if(!removed[e.fr]) decompose(e.fr);
}
int best_path(int _n, int _k, int h[][2], int l[]){
n = _n, k = _k;
for(int i = 0; i < n - 1; i++){
int u = h[i][0], v = h[i][1], w = l[i];
adj[u].emplace_back(v, w);
adj[v].emplace_back(u, w);
}
ans = INF;
for(int i = 0; i <= k; i++) f[i] = INF;
decompose(0);
return (ans == INF ? -1 : ans);
}
// int32_t main(void){
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// cout << best_path(11, 12, H, L);
// }
# | 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... |