HDU 5187 ZHY's contest (数学 快速幂+快速乘)

As one of the most powerful brushes, zhx is required to give his juniors nn problems.
zhx thinks the ithith problem's difficulty is ii. He wants to arrange these problems in a beautiful way.
zhx defines a sequence {ai}{ai} beautiful if there is an ii that matches two rules below:
1: a1..aia1..ai are monotone decreasing or monotone increasing.
2: ai..anai..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 pp.

Input

Multiply test cases(less than 10001000). Seek EOFEOF as the end of the file.
For each case, there are two integers nn and pp separated by a space in a line. (1≤n,p≤10181≤n,p≤1018)

Output

For each test case, output a single line indicating the answer.

Sample Input

2 233
3 5

Sample Output

2
1


        
  

Hint

In 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
        
 
#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<queue>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<vector>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define ll unsigned long long
#define MAX 1000000000
#define ms memset
const int maxn=80005;
using namespace std;
/*
题目大意:给定一个1到n的序列,
要求计数单调减,单调增,先增后减,先减后增的个数。

先选出最小的,然后对剩余的进行组合排列,
即C(n-1,1)+C(n-1,2)+...C(n-1,n-2),
最后可推出公式2^n-2。

由于本题的数据量的原因,
不仅要快速幂,还要快速乘,
原理都差不多。
*/
ll cheng_mod(ll x,ll y,ll mod)
{
    ll t=0;
    while(y)
    {
        if(y&1) t=(t+x)%mod;
        x=(x+x)%mod;
        if(t>=mod) t-=mod;
        y>>=1;
    }
    return t;
}

ll pow_mod(ll x,ll y,ll mod)
{
    ll t=1;
    while(y)
    {
        if(y&1) t=cheng_mod(t,x,mod);
        x=cheng_mod(x,x,mod);
        y>>=1;
    }
    return t%mod;
}
ll n,m;
int main()
{
    while(scanf("%lld%lld",&n,&m)!=EOF)
    {
        if(n==1) printf("%d\n",(m==1?0:1));
        else printf("%lld\n",(pow_mod(2,n,m)-2+m)%m);
    }
    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/81447917