e-olymp 8514. Never drink too much!

The task is taken from e-olymp


Mahmoud together with his friends visited Georgia. They would stay in a hotel at Rustavelli. When the cowboys reached the hotel, they hung their hats in the entrance and settled in. The beer bottles on the table could not escape from Mahmoud’s attention when passing through the corridor. At the suggestion of Mahmoud, all the cowboys began drinking. They drank too much, thus none of them was mindful. Then they decided going downtown. On the way out, everyone had a hat on, but they mixed up the hats as they were so drunk.

The man who is able to have on his own hat while he is drunk is considered clever and who is not able to do so is considered stupid.

You are given the number of cowboys — n (including Mahmoud). You should find in how many ways the cowboys may have on the hats so that all of them are stupid. Two ways are considered different if there is at least one cowboy who has a hat in this case and another hat in the other case.

As the answer may become very large, you should output the result modulo 109 + 7.


Given the number of cowboys — n (1 ≤ n ≤ 107).


The answer to the problem as specified above.


Inputs Outputs
1 0
4 9
9 133349
555 335132588
10000000 824182295




We have all possible permutations [latex]C_n^0 \cdot n![/latex] , minus one fixed (one of them is not stupid) we get [latex]C_n^0 \cdot n!-C_n^1 \cdot (n-1)![/latex] but we subtract for minimum fixed pair (two of them are not stupid) we need to add them [latex]C_n^0 \cdot n!-C_n^1 \cdot (n-1)! + C_n^2 \cdot (n-2)! [/latex] etc.
So the [latex]k[/latex] member is [latex]C_n^k \cdot (n-k)! \cdot (-1)^k[/latex]
Let`s find the attitude of [latex]k[/latex] member to the previous one. It`s [latex]-k -1[/latex]
The last one will be [latex]-1[/latex] it depends on parity of [latex]n[/latex].
First two are the same ( [latex]n![/latex] ) so we skip them, but in this case we need to check if[latex]n[/latex] equals [latex]1[/latex]
And next we make a loop to find the answer by multiplying start value and add it to the answer.
The complexity is [latex]O(n)[/latex]



3 thoughts on “e-olymp 8514. Never drink too much!

  1. Поддержу Игоря Евгеньевича. Переопределять int — очень нехорошая практика. В результате даже пришлось определять main() как int32_t. В большом проекте за такие дефайны сотрудники точно не поблагодарят. Если Вам лень писать long long или Вы предполагаете дальнейшее переопределние какого-то типа данных, можете использовать незарезервированный псевдоним. И безопаснее его оформлять через typedef, а не #define. Например:
    typedef long long ll;

Добавить комментарий