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

本文介绍了一个关于计算特定序列数量的问题,给出了高效的算法实现方案。针对一个由1到n的整数构成的序列,讨论了其可能形成的单调递增、递减及先增后减、先减后增的合法序列数量,并提供了具体的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值