Submission #1246728

#TimeUsernameProblemLanguageResultExecution timeMemory
1246728vht2025Parkovi (COCI22_parkovi)C++20
0 / 110
182 ms26612 KiB
#include <iostream> #include <vector> #include <algorithm> using namespace std; using ll = long long; vector<pair<int, int>> adj[200005]; int n, k; 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. 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; // Khoảng cách từ u đến đỉnh xa nhất trong cây con của v là dfs(v, u) + w max_uncovered_dist = max(max_uncovered_dist, dfs(v, u) + w); } // Nếu khoảng cách này bằng D, ta bắt buộc phải đặt công viên tại u // để che chở cho đỉnh xa xôi đó. Đây là "thời điểm cuối cùng có thể". if (u != 1 && max_uncovered_dist == D_check) { parks_needed++; if (is_reconstructing) { park_locations.push_back(u); } // Trả về 0, báo hiệu nhánh này đã được che chở từ u. return 0; } return max_uncovered_dist; } void solve() { 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; // 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; dfs(1, 0); // Chạy DFS từ gốc 1 parks_needed++; // Luôn cần ít nhất 1 công viên để che chở cho gốc 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; dfs(1, 0); park_locations.push_back(1); // Luôn đặt 1 công viên ở gốc // 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 = 1; // cin >> t; // Bỏ comment nếu đề bài có nhiều test case 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...