#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const long long INF = 1e18;
vector<pair<int, int>> adj[200005];
int n;
long long D_check;
int parks_needed;
vector<int> park_locations;
// f[u]: khoảng cách lớn nhất từ u đến một đỉnh chưa được bao phủ trong cây con của u
long long dfs_check(int u, int p) {
long long max_dist = 0;
for (auto& edge : adj[u]) {
int v = edge.first;
int w = edge.second;
if (v == p) continue;
// f[v] + w là khoảng cách từ u đến đỉnh xa nhất trong cây con của v
max_dist = max(max_dist, dfs_check(v, u) + w);
}
// Nếu đỉnh xa nhất trong cây con của u có khoảng cách đến u bằng D,
// ta phải đặt công viên tại u.
if (max_dist >= D_check) {
parks_needed++;
park_locations.push_back(u);
return 0; // Nhánh này đã được bao phủ
}
return max_dist;
}
void solve() {
int k;
cin >> n >> k;
for (int i = 1; i <= n; ++i) {
adj[i].clear();
}
long long total_weight = 0;
for (int i = 0; i < n - 1; ++i) {
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
total_weight += w;
}
long long low = 0, high = total_weight, ans_D = high;
// Tìm kiếm nhị phân trên kết quả D
while (low <= high) {
D_check = low + (high - low) / 2;
parks_needed = 0;
// Cần một gốc cố định để DFS.
// Ta cần tìm một đỉnh không phải lá để bắt đầu DFS.
// Nếu tất cả các đỉnh đều là lá (n<=2), ta xử lý riêng.
// Ở đây n>=3.
int root = 1;
while(adj[root].size() == 1 && root <= n) {
root++;
}
if(root > n) root = 1; // Trường hợp đồ thị là đường thẳng
long long root_dist = dfs_check(root, 0);
// Nếu gốc vẫn chưa được bao phủ, cần thêm 1 công viên
if (root_dist > 0) {
parks_needed++;
}
if (parks_needed <= k) {
ans_D = D_check;
high = D_check - 1;
} else {
low = D_check + 1;
}
}
cout << ans_D << "\n";
// Chạy lại check() với D tối ưu để lấy danh sách công viên
D_check = ans_D;
parks_needed = 0;
park_locations.clear();
int root = 1;
while(adj[root].size() == 1 && root <= n) {
root++;
}
if(root > n) root = 1;
long long root_dist = dfs_check(root, 0);
if (root_dist > 0) {
parks_needed++;
park_locations.push_back(root);
}
// Nếu số công viên tìm được ít hơn k, ta có thể đặt thêm ở bất kỳ đâu
int current_parks = park_locations.size();
vector<bool> is_park(n + 1, false);
for(int loc : park_locations) is_park[loc] = true;
for (int i = 1; i <= n && current_parks < k; ++i) {
if (!is_park[i]) {
park_locations.push_back(i);
current_parks++;
}
}
for (int i = 0; i < k; ++i) {
cout << park_locations[i] << (i == k - 1 ? "" : " ");
}
cout << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
# | 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... |