Problem: This is the harder version of the problem. In this version, . You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
The problem is to finish one-choice-questions. Each of the questions contains options, and only one of them is correct. The answer to the -th question is , and if your answer of the question is , you earn point, otherwise, you earn points for this question. The values are known to you in this problem.
However, you have a mistake in your program. It moves the answer clockwise! Consider all the answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.
Formally, the mistake moves the answer for the question to the question . So it moves the answer for the question to question , the answer for the question to the question , ..., the answer for the question to the question .
We call all the answers together an answer suit. There are possible answer suits in total.
You're wondering, how many answer suits satisfy the following condition: after moving clockwise by , the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo .
For example, if , and your answer suit is , it will submitted as because of a mistake. If the correct answer suit is , the answer suit earns point and the answer suite earns points. Since , the answer suit should be counted.
Input Format: The first line contains two integers , (, ) — the number of questions and the number of possible answers to each question.
The following line contains integers , ( — answers to the questions.
Output Format: Output one integer: the number of answers suits satisfying the given condition, modulo .
Note: For the first example, valid answer suits are .