Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

First, note that if KK is not a divisor of the N1N - 1, then the edges can never be evenly partitioned. Thus, we only need to check divisors of N1N - 1.

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 reached KK yet. Since only 11 of such path exist, all of the other paths which source from the subtrees of ii must be evenly paired.

For each node jj such that jj is a child of node ii, there must be another node kk such that toBeMerged[j]+toBeMerged[k]+2=K\mathtt{toBeMerged[j]+toBeMerged[k]} + 2 = K in order to complete the path. If no such kk exist, then we will store the current length of the path in toBeMerged[i]\mathtt{toBeMerged[i]}, but there can only be one such jj.

el arbol

In the above tree, assume K=3K = 3. Then toBeMerged[2]=2\mathtt{toBeMerged[2]} = 2, toBeMerged[5]=1\mathtt{toBeMerged[5]} = 1, toBeMerged[7]=0\mathtt{toBeMerged[7]} = 0, and toBeMerged[8]=0\mathtt{toBeMerged[8]} = 0. Since there are two paths with length 00 and only one path with length 11, we have a path of length 00 left over, so toBeMerged[1]=0+1=1\mathtt{toBeMerged[1]} = 0 + 1 = 1.

It can be proven the maximum number of divisors for an integer up to the constraints of NN will be small enough for us to run an linear time algorithm for each divisor.

True upper bound

This upper bound is around No(1)N^{o(1)}, 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: O(NNo(1))\mathcal{O}(N \cdot N^{o(1)})

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 subtrees
map<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!