Editorial for DMOPC '18 Contest 5 P5 - A Hat Problem


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.

Author: r3mark

Each person has two choices, so there are 2N possibilities. Trying each of these 2N possibilities passes in time for subtask 1.

Time Complexity: O(N2N)

For the second subtask, let dp[i] be the least unhappiness if person i leaves without trading the next person. Say that they leave with the hat originally from person j. For that hat to have travelled all the way there, person j1 must have not traded with the next person and everyone from j to i1 must have. It is then easy to see that in this case, dp[i]=dp[j1]+|vj+1wj|+|vj+2wj+1|++|viwi1|+|vjwi|.

The sum |vj+1wj|+|vj+2wj+1|++|viwi1| can be computed in O(1) with a prefix sum array.

Time Complexity: O(N2)

For the final subtask, we analyze the dp from above. Splitting the absolute value into two cases yields the following:

dp[i]=minji{(prefix[i]wi)+(dp[j1]prefix[j]+vj)if vjwi(prefix[i]+wi)+(dp[j1]prefix[j]vj)if vj<wi

Note that each sum can be split into a component that depends only on i, and a component that depends only on j. So we create two segment trees storing the component depending on j. More precisely, we update each segment tree at index vj with value dp[j1]prefix[j]+vj and dp[j1]prefix[j]vj. Then we can query the two segment trees to compute each dp value.

Time Complexity: O(NlogN)


Comments

There are no comments at the moment.