Submission #1246721

#TimeUsernameProblemLanguageResultExecution timeMemory
1246721vht2025Parkovi (COCI22_parkovi)C++20
0 / 110
15 ms7748 KiB
#include <iostream> #include <vector> #include <algorithm> using namespace std; using ll = long long; vector<pair<int, int>> adj[200005]; int n; ll D_check; int parks_needed; vector<int> park_locations; bool is_reconstructing; // Hàm DFS trả về 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. // Trả về một số âm nếu cây con của u đã được bao phủ. ll dfs(int u, int p) { ll max_uncovered_dist = 0; for (auto& edge : adj[u]) { int v = edge.first; int w = edge.second; if (v == p) continue; ll dist_from_child = dfs(v, u); // Chỉ xét các nhánh chưa được bao phủ if (dist_from_child >= 0) { max_uncovered_dist = max(max_uncovered_dist, dist_from_child + w); } } // Nếu khoảng cách xa nhất vượt quá D, ta bắt buộc phải đặt công viên tại u. if (max_uncovered_dist > D_check) { parks_needed++; if (is_reconstructing) { park_locations.push_back(u); } // Trả về giá trị âm để báo hiệu nhánh này đã được che chở return -1; } return max_uncovered_dist; } void solve() { int k; cin >> n >> k; for (int i = 1; i <= n; ++i) { adj[i].clear(); } ll 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; } ll low = 0, high = total_weight, ans_D = high; int root = 1; // 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; is_reconstructing = false; ll remaining_dist = dfs(root, 0); // Nếu bản thân gốc và các đỉnh gần nó vẫn chưa được che chở if (remaining_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 DFS lần cuối với D tối ưu để lấy danh sách vị trí công viên D_check = ans_D; parks_needed = 0; park_locations.clear(); is_reconstructing = true; ll remaining_dist = dfs(root, 0); if (remaining_dist >= 0) { park_locations.push_back(root); } // Nếu thuật toán tham lam dùng ít hơn k công viên, ta có thể đặt thêm ở bất kỳ đâu vector<bool> is_park(n + 1, false); for(int loc : park_locations) { is_park[loc] = true; } for (int i = 1; i <= n && park_locations.size() < k; ++i) { if (!is_park[i]) { park_locations.push_back(i); } } 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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...