PROBLEM LINK:
Author: Shashwat Chandra
Tester: Shashwat Chandra, Bharat Goyal, Taranpreet Singh
Editorialist: Shashwat Chandra
DIFFICULTY:
EASY - MEDIUM
PREREQUISITES:
QUICK EXPLANATION:
Note that we always remove the current leaves of the tree in every operation.
You can calculate the time at which every node becomes a leaf recursively and then print the number of nodes for which this time is <= K.
EXPLANATION:
First, let us solve the problem for K = 1. Observe that in this case, we should keep moving as long as we can which means until all the nodes with chips on them are leaves (nodes which have no children).
The proof is given below for the sake of completion.
Proof
For the sake of contradiction, assume the optimal solution involves covering a node which has a non-zero amount of children c_i > 0.
However, we could just move the chip to its children, changing the answer by c_i -1 which is a non-negative value.
So how do we use this to solve the problem for K > 1 ?
Observe that for K > 1 , we can treat the problem as K problems all with K_i = 1. This is pretty intuitive thus the proof is omitted.
Now the reduced problem is as follows -
You do K operations, in every operation you remove all the current leaves from the tree. Find the number of nodes that you will remove in total.
Define time(i) as the time when the i^{th} becomes a leaf, time(v) = 1 for all leaves v of the initial tree.
We can calculate time(i) recursively :
- For all nodes u which are leaves of the original tree, time(u) = 1.
- Otherwise for a node u with m > 0 children,
time(u) = max(time(c_1), time(c_2), ... , time(c_m) ) + 1.
Here, c_1,c_2, ... , c_m are the indices of the children of u.
Now, the answer is simply the number of nodes i for which time(i) <= K holds.