zhx's contest
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1866 Accepted Submission(s): 596
Problem Description
As one of the most powerful brushes, zhx is required to give his juniors
n
problems.
zhx thinks the ith problem's difficulty is i . He wants to arrange these problems in a beautiful way.
zhx defines a sequence {ai} beautiful if there is an i that matches two rules below:
1: a1..ai are monotone decreasing or monotone increasing.
2: ai..an are monotone decreasing or monotone increasing.
He wants you to tell him that how many permutations of problems are there if the sequence of the problems' difficulty is beautiful.
zhx knows that the answer may be very huge, and you only need to tell him the answer module p .
zhx thinks the ith problem's difficulty is i . He wants to arrange these problems in a beautiful way.
zhx defines a sequence {ai} beautiful if there is an i that matches two rules below:
1: a1..ai are monotone decreasing or monotone increasing.
2: ai..an are monotone decreasing or monotone increasing.
He wants you to tell him that how many permutations of problems are there if the sequence of the problems' difficulty is beautiful.
zhx knows that the answer may be very huge, and you only need to tell him the answer module p .
Input
Multiply test cases(less than
1000
). Seek
EOF
as the end of the file.
For each case, there are two integers n and p separated by a space in a line. ( 1≤n,p≤1018 )
For each case, there are two integers n and p separated by a space in a line. ( 1≤n,p≤1018 )
Output
For each test case, output a single line indicating the answer.
Sample Input
2 233 3 5
Sample Output
2 1HintIn the first case, both sequence {1, 2} and {2, 1} are legal. In the second case, sequence {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1} are legal, so the answer is 6 mod 5 = 1
a[1]~a[n]保持单调递增
a[1]~a[n]保持单调递减
a[1]~a[i]保持单调递增,a[i]~a[n]保持单调递减(序列中有一个a[i]满足该条件即可)
a[1]~a[i]保持单调递减,a[i]~a[n]保持单调递减(序列中有一个a[i]满足该条件即可)
思路:
考虑前两种,只有两种情况了。故当前ans=2
考虑第三种,可以知道先递增再递减,a[i]为最大值,也就是n了。 那么此时我们枚举n放在第二个位置到第n-1个位置的情况(n放在第一个和第二个就和前两种情况重合了)
当n放在第i个位置时,相当于从剩下的1~n-1这n-1个数中取出i-1个数放在i的左边,因为左右保持有序,所以取完后位置也就固定了。
那么第三种情况一共有C(n-1,1)+(n-1,2)+...+(n-1,n-2) 也就是2的(n-1)次方-2
第四种情况与第三种一样
于是一共有2*(2的(n-1)次方-2)+2=2的n次方-2
但是注意这里n和p都可能为10的18次方,直接相乘会炸ull。所以我们不能直接用快速幂。
所以我们考虑在快速幂里面的乘法相乘的部分用矩阵乘法处理,把乘法转换为加法。
原理和快速幂类似。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
long long mod;
long long mul_mod(long long a,long long n)
{
long long ans=0;
while(n)
{
if(n&1) ans=(ans+a)%mod;
a=(a+a)%mod;
n>>=1;
}
return ans;
}
long long pow_mod(long long a,long long n)
{
long long ans=1;
while(n)
{
if(n&1) ans=mul_mod(ans,a);
a=mul_mod(a,a);
n>>=1;
}
return ans;
}
int main()
{
long long n;
while(~scanf("%lld %lld",&n,&mod))
{
if(n==1)
{
if(mod==1) printf("0\n");
else printf("1\n");
}
else printf("%lld\n",(pow_mod(2,n)-2+mod)%mod);
}
return 0;
}