Explanation
First, note that if is not a divisor of the , then the edges can never be evenly partitioned. Thus, we only need to check divisors of .
We can arbitrarily root the tree at node . Let store the length of the path passes through node and its length has not reached yet. Since only of such path exist, all of the other paths which source from the subtrees of must be evenly paired.
For each node such that is a child of node , there must be another node such that in order to complete the path. If no such exist, then we will store the current length of the path in , but there can only be one such .
In the above tree, assume . Then , , , and . Since there are two paths with length and only one path with length , we have a path of length left over, so .
It can be proven the maximum number of divisors for an integer up to the constraints of will be small enough for us to run an linear time algorithm for each divisor.
True upper bound
This upper bound is around , using the little o notation. The exact formula can be found here. A table for the upper bound of the number of divisors can be found here.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;const int N = 1e5;vector<int> g[N];int to_be_merged[N];bool dfs(int node, int p, int k) {// count length of path not merged yet in subtreesmap<int, int> to_be_merged_count;
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!