Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Note that if we can split the tree into paths of at least xx, then we can also split it into paths of at least yy where y<xy < x. Thus, it suffices to binary search over the minimum path length.

We can arbitrarily root the tree at node 11. Let toBeMerged[i]\mathtt{toBeMerged[i]} store the length of the path passes through node ii 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 ii must be evenly paired with sum of lengths k\geq k.

We want to maximize toBeMerged[i]\mathtt{toBeMerged[i]} while evenly pairing all of the children with path lengths k\geq k. 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 00. If our binary search returns 00, then we know all the children are already evenly paired.

Implementation

Time Complexity: O(Nlog2N)\mathcal{O}(N \log^2 N)

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 >= k
bool 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 O(N2logN)\mathcal{O}(N^2 \log N). 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 >= k
bool 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!