# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
848097 | comgaTramAnh | 경주 (Race) (IOI11_race) | C++14 | 0 ms | 0 KiB |
이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <math.h>
#include <vector>
#include <utility>
int n, k;
std::vector <std::pair <int, int> > adj[200005];
int minDist[1000005];
int sizeSubTree[200005];
bool used[200005];
int ans;
void dfsSize(int u, int father) {
sizeSubTree[u] = 1;
for (int i = 0; i < (int) adj[u].size(); i++) {
std::pair <int, int> neighbor = adj[u][i];
if (neighbor.first == father || used[neighbor.first] == true) {
continue;
}
dfsSize(neighbor.first, u);
sizeSubTree[u] += sizeSubTree[neighbor.first];
}
}
int findCentroid(int u, int father, int numbNodes) {
for (int i = 0; i < (int) adj[u].size(); i++) {
std::pair <int, int> neighbor = adj[u][i];
if (neighbor.first == father || used[neighbor.first] == true) {
continue;
}
if (2 * sizeSubTree[neighbor.first] >= numbNodes) {
return findCentroid(neighbor.first, u, numbNodes);
}
}
return u;
}
void dfs(int u, int father, int numbEdges, int totalLength, bool state) {
if (totalLength > k) {
return;
}
if (state == false) {
ans = std::min(ans, numbEdges + minDist[k - totalLength]);
}
else {
minDist[totalLength] = std::min(minDist[totalLength], numbEdges);
}
for (int i = 0; i < (int) adj[u].size(); i++) {
std::pair <int, int> neighbor = adj[u][i];
if (neighbor.first == father || used[neighbor.first] == true) {
continue;
}
dfs(neighbor.first, u, numbEdges + 1, totalLength + neighbor.second, state);
}
}
void centroidDecomposition(int u) {
dfsSize(u, -1);
int centroid = findCentroid(u, -1, sizeSubTree[u]);
used[centroid] = true;
for (int i = 0; i < (int) adj[centroid].size(); i++) {
std::pair <int, int> neighbor = adj[centroid][i];
if (used[neighbor.first] == true) {
continue;
}
dfs(neighbor.first, centroid, 1, neighbor.second, false);
dfs(neighbor.first, centroid, 1, neighbor.second, true);
}
for (int i = 0; i < (int) adj[centroid].size(); i++) {
std::pair <int, int> neighbor = adj[centroid][i];
if (used[neighbor.first] == true) {
continue;
}
centroidDecomposition(neighbor.first);
}
}
int main () {
std::cin >> n >> k;
for (int i = 1; i < n; i++) {
int u, v, length;
std::cin >> u >> v >> length;
adj[u].push_back(std::make_pair(v, length));
adj[v].push_back(std::make_pair(u, length));
}
for (int i = 0; i <= k; i++) {
minDist[i] = n + 5;
}
minDist[0] = 0;
ans = n + 5;
centroidDecomposition(0);
std::cout << (ans == n + 5 ? -1 : ans);
return 0;
}