Editorial for Back To School '18: Beautiful Trees
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
For Subtask 1, because all connection points satisfy the constraint for some integer , the problem is equivalent to finding the diameter of the tree. To find the diameter of a tree, we can do a Depth First Search from an arbitrary connection point, find the farthest connection point, and do another Depth First Search from that point. The length of the longest path from that connection point would be the diameter of the tree.
Time Complexity:
For subtask 2, we can store all values that satisfy the constraint for some integer . We can loop from to and store all in a Balanced Binary Search Tree. Then, we can check whether a connection point is valid in logarithmic time by querying if that value exists in the BBST. To find the longest good segment of the tree, we can find the diameter of each "component" of the tree, where each "component" only consists of valid nodes.
Time Complexity:
For subtask 3, we must find a quick way of checking whether the constraint is satisfied, as storing values in a BBST is too slow. There are multiple ways of checking, and we will describe a few here.
One way is by performing a binary search on the value of for a certain .
Another way is by checking whether for .
The third way is by using the quadratic formula:
We can plug the values into the quadratic formula:
If the equation evaluates to an integer, then the constraint is satisfied, otherwise, it is not.
Time Complexity: or
Comments