Explanation
Note that if we can split the tree into paths of at least , then we can also split it into paths of at least where . Thus, it suffices to binary search over the minimum path length.
We can arbitrarily root the tree at node . Let store the length of the path passes through node and its length has not been paired yet. Since only one of such path can exist, all of the other paths which source from the subtrees of must be evenly paired with sum of lengths .
We want to maximize while evenly pairing all of the children with path lengths . To do this, we can run another binary search over the unpaired path lengths of the children and check if we can remove any of them and the condition holds. If we removed one and the rest is still unpairable, then we return false.
Note that this requires the number of unpaired lengths to be initially odd. If there are an even number of children, then we can append an arbitrary . If our binary search returns , then we know all the children are already evenly paired.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;const int N = 1e5;vector<int> g[N];int to_be_merged[N];// check if elements can be paired with sum >= kbool check(vector<int> &v, int remove, int k) {
Warning: Bad Test Cases
The following code will also AC due to weak test data, but it is technically . It exploits the fact that we can break early once we found an index to remove and loop linearly through all the children from high to low. This solution can be hacked with a suitable graph where one node has a large number of children, though.
#include <bits/stdc++.h>using namespace std;const int N = 1e5;vector<int> g[N];int to_be_merged[N];// check if elements can be paired with sum >= kbool check(vector<int> &v, int remove, int k) {
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!