Editorial for COCI '20 Contest 6 #3 Anagramistica


Remember to use this editorial 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.

The first subtask can be solved by iterating over all possible subsets and counting the number of similar pairs in each one.

Since each element is either in the chosen subset or not, that leads us to a dynamic programming solution, where dp[n][k] is the number of ways to choose among the first n words a subset with exactly k similar pairs. The transition would be:

\displaystyle dp[n][k] = dp[n-1][k]+dp[n-1][k-x]

where x is the number of new similar pairs that appear when we add the n^\text{th} word to the subset. Unfortunately, since we don't know which words are in the subset, we can't know x.

But, we can use a similar approach if we notice that if we sort the letters in each word, then the words are similar if and only if they are equal.

After sorting, we get a multiset of words, with m distinct elements, and the i^\text{th} element appears a_i times. Let dp[m][k] be the number of ways to choose among the first m different words a subset with exactly k equal words. The transition is:

\displaystyle dp[m][k] = \sum_{i=0}^{i \le a_i, \frac{i(i-1)}{2} \le k} \binom{a_i}{i} dp[m-1][k-i(i-1)/2]

The initial values are dp[0][k] = 1, for k = 0, or 0 otherwise.

Since the numbers in the binomial coefficient are at most n, we can precompute them using Pascal's triangle. The complexity for each k is \mathcal O(n), since the sum of all a_i is equal to n, so the total complexity of the solution is \mathcal O(n^2+nk).


Comments

There are no comments at the moment.