We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Roads and Libraries
Roads and Libraries
Sort by
recency
|
889 Discussions
|
Please Login in order to post a comment
I solved it using DSU - wikipedia:
It’s interesting how breaking the tree into components becomes much clearer once you focus on counting the subtrees and checking where an even split is possible. Your explanation helps simplify the logic behind the cuts, especially for anyone struggling with the recursive approach. Sometimes stepping back and viewing the structure as smaller manageable parts makes the whole problem feel less overwhelming. By the way, coordinating complex tasks like this reminds me of organizing group travel—using a Part bus setup can make things run just as smoothly.
If you get WA on 6 hidden tests try this:
1ll*n*c_libinstead ofn*c_lib*1llorn*c_lib(same for1ll * c_lib + (comp-1) * c_road)I spent quite some time to figure out why my solution didnt pass the 7 heavy input test cases. It turned out that since i tried to convert the edge list to adjacency matrix, the test ran out of memory. So instead of adjacency matrix, i use std::map as adjacency list. map> toAdjList(int n, vector> cities) { map> result = {}; for (const auto &ct : cities) { int a = ct[0]; int b = ct[1]; if (result.find(a) == result.end()) { result[a] = vector(); } result[a].push_back(b); if (result.find(b) == result.end()) { result[b] = vector(); } result[b].push_back(a); }
}
long roadsAndLibraries(int n, int c_lib, int c_road, vector> cities) { if (n == 0) return 0; if (n == 1) return c_lib;
} `