## Editorial for Appleby Contest '20 P5 - Ridiculous Tree

**only**when stuck, and

**not to copy-paste code from it**. Please be respectful to the problem author and editorialist.

**Submitting an official solution before solving the problem yourself is a bannable offence.**

Author:

Let's begin by trying to find a DP solution to this problem:

We can define the DP state as follows:

Let be the number of permutations of the nodes in the subtree of node that satisfies the property Ridiculous Ray wants.

From this state, we can get the following recurrence:

Let be the set of nodes adjacent to node .

Let be the number of nodes in the subtree of node .

Observation: the resulting formula we get from expanding this recurrence on any tree will be a sequence of multiplications. Instead of storing the prime factorization of the overall answer, we can just count the number of times each integer occurs in the product and add its prime factorization times to the answer (where is its frequency).

Then, to optimize the solution to get full points, a difference array can be used as the answer is the product of factorials.

The first subtask was meant to reward brute force solutions.

The second subtask was meant to reward contestants that found the recurrence but computed the DP values directly, either by storing the prime factorization as a map data structure or by using arbitrary precision integers.

**Time complexity:**

## Comments

A simpler formula: then answer is A proof: we'll calculate the probability that each constraint is satisfied. Then, each node has an probability of being the smallest node in its subtree, and furthermore these probabilities are

independent. Thus, the number of good assignments (such that all nodes are smaller than their children) is exactly times the product of these probabilities.:O very cool