Editorial for COCI '21 Contest 2 #4 Magneti
Submitting an official solution before solving the problem yourself is a bannable offence.
Define the length of a permutation of magnets as the least number of adjacent slots used for placing the magnets in that order without attracting each other. Say that the order of the magnets is fixed and that the length of the permutation is . If the length of the permutation is greater than , then it's impossible to place the magnets on the board in that order. If the length of the permutation is less than or equal to , then what's left is to arrange the remaining empty slots among the magnets so that there are a total of slots on the board. Each of these remaining empty slots can be arranged among "gaps" in the array, that is either before all magnets or after all magnets or between any two adjacent magnets. The number of ways to arrange these empty slots can be calculated with a combinatorial trick called Stars and bars and it equals .
For the first subtask, the length of each permutation of magnets is (if denotes the radius of activity of the magnets), so the answer is . The binomial coefficients can be precomputed using Pascal's triangle.
For the second subtask, it's possible to go over each permutation of the magnets, for each one calculate its length and the number of ways to arrange the remaining slots. The total complexity of this is .
For the entire solution, we use dynamic programming to calculate for each between and how many permutations have length , and then multiply this number by .
We sort the magnets by increasing radius and build the permutation with the following dp:
number of ways to arrange the first magnets in groups such that the sum of the lengths of the groups is .
One group represents a segment of the permutation that is being built and is comprised of magnets and the least amount of empty space between them. The transition of the dp actually consists of adding a new magnet to one of the groups, which can be done in three ways:
- creating a new group that is made just from this magnet,
- adding a magnet to one of the ends of one of the already existing groups, or
- connecting two existing groups by placing the new magnet between them
The number of permutations which have length will be stored in (all of the magnets are in a single group of length ). The time complexity of this solution is because there are states and the transitions are calculated in .
Comments