## Editorial for Baltic OI '18 P6 - Paths

**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.**

#### Subtask 1

To get the points for subtask 1, it's sufficient to write a brute force solution that naively counts all possible valid paths. (See full solution below, but remove the parts regarding memoization and dynamic programming to make it exponentially slow.)

#### Subtask 2

Since the number of colors was at most , the length of the path was also at most ; and thus either or . Paths of length are simple to count: they are just the number of edges between nodes with different colors. Paths of length require a bit more thought. One way we can handle them is by looping over which node is in the middle of the path, and which colors the nodes at the start and end of the path have. Then the number of paths that have this node in the middle is the product of the number of neighbors of the first color and the number of neighbors of the second color.

#### Subtask 3

This is a natural extension to subtask 2: instead of looping over which node is in the middle of the path, we loop over which *edge* is in the middle. The rest works exactly the same.

#### Subtask 4

Assume there's a function that gives the number of valid paths starting in a certain node. Then the answer to the problem is the sum of over all nodes. The trick is to calculate efficiently, as the input to the problem is quite large.

Let take two parameters, (the current node) and (a bitset indicating the colors we have used so far, initially ). Since the number of colors in a path is at most , the number of possible such bitsets is . This means that the number of possible combinations of parameters to is small enough to make a lookup table: we can use dynamic programming.

Memoizing on parameters and , we implement by summing for all neighbors of , and where is the same bitset as but with the color bit of marked. We make sure to not take any paths where we reuse a color, and we make sure to not calculate answers for states that we have previously calculated. Given this, the answer to the problem is (make sure to not count paths of length !). Also remember to use 64-bit integer types.

This yields a time complexity of .

Interesting note: the problem was essentially about counting paths of length at most , given that all nodes need to have different colors. This is much simpler than counting *all* paths of length at most ! The naive time complexity of the latter is on the order of rather than . This can be used as a general algorithmic technique to speed up various problems: pick colors randomly a bunch of times (say, times), then use an algorithm that restricts nodes to have different colors.

## Comments