## Ex - Yet Another Path Counting Editorial by en_translator

### Basic idea

For each label \(1,2,\ldots,N^2\), we consider the squares \((x_1,y_1),\ldots,(x_k,y_k)\) with that label, and count the paths which starts and ends with two (or one) of these squares.

### Solution 1 (directly adopting this will lead to TLE)

Consider all combinations of starting and ending squares chosen from squares \((x_1,y_1),\ldots,(x_k,y_k)\) of each label. When the starting and ending squares are fixed, the number of paths can be represented by a binomial coefficients (which can be found online by searching like “combinatorics shortest path”), so they can be found in an \(\mathrm O (1)\) time each by precalculating the binomial coefficients.

Let us analyze the complexity of this solution. Let \(n_i\) be the number of squares labeled \(i\), then the total number of steps for the brute force is \(\sum{n_i^2}\). The worst case is when all squares have the same label, in which case the complexity is \(\mathrm O (N^4)\). This does not fit in the time limit.

### Solution 2 (directly adopting this will lead to TLE)

For each fixed label, consider the following Dynamic Programming (DP).

\(\mathrm {dp}_{i,j}\) : the number of paths starting from a square with the currently considering label and ending at Square \((i,j)\)

Starting from the state where the squares with the current label is filled with \(1\) and the other squares with \(0\), compute the transitions and finally take the sum over all the squares with the current label, then the total number of paths starting and ending with the square with the current label can be found.

The DP costs \(\mathrm O(N^2)\), and there are at worst \(N^2\) kinds of label, so the complexity of this solution is \(\mathrm O(N^4)\), which does not fit in the time limit.

### Accepted solution

For each label, if there are \(N\) or less squares with that label, then apply Solution 1, and if there are more than \(N\) such squares, then apply solution 2. This solution is fast enough; indeed, we can assert that the solution has a complexity of \(\mathrm O(N^3)\) by the following analysis.

- The total number of steps we described in Solution 1 is \(\sum {n_i^2}\), but now we have \(n_i\leq N\), so \(\sum{n_i^2} \leq N\sum{n_i}\). Since \(\sum n_i \leq N^2\), we have \( N\sum{n_i} \leq N^3\), so Solution 1 is computed in a total of \(\mathrm O(N^3)\) time.
- There are at most \(N\) labels that Solution 2 is adopted. (Otherwise, there will be more than \(N\) labels, each of which has \(N\) squares with the label written on it, which means that there are more than \(N^2\) squares, thus contradiction) Sine the DP of cost \(\mathrm O(N^2)\) is done at most \(N\) times, solution 2 is computed in a total of \(\mathrm O(N^3)\) time too.

posted:

last update: