zhx's contest----快速幂+快速乘

zhx's contest

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2343    Accepted Submission(s): 738


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 .
 

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. ( 1n,p1018 )
 

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
 

Source

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5187


题目的意思我就不说了,这是BestCoder的一道题,可以点进去看中文题意,提示一下,中文题意也特别的不好懂,我一开始就理解错了,我标(绝尘)也理解错了,看了题解,恍然大悟,是让你找到可以形成升降,升升,降升,降降的一个序列,并不是每一个ai都需要满足这个条件。

有此可以得出,升升和降降只有两种可能,而升降和降升都多了,升降和降升的转折点ai我们可以很容易的找到就是最大点或者是最小点,而一旦确定了ai,那么剩下的我们只需要确定是在ai的左边还是右边就可以了,一旦确定,序列就是唯一的,那么假如说是最大点,除了最大点,剩下有n-1个点那么每个点有两种选择,总共就有2^(n-1)种可能,最小点也是,所以一共有2^(n)种,降降和升升也被计算了,所以一共有2^n-2种可能,取一下模就好了。

我是为了学快速乘做的这个题,发现快速乘和快速幂完全一样的思想。。。

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#define LL long long
using namespace std;
LL kuaisucheng(LL x,LL n,LL mod){
    LL ans=0;
    while(n){
        if(n&1)
            ans+=x;//改成加法就是快速乘
        x=(x+x)%mod;
        ans%=mod;
        n>>=1;
    }
    return ans;
}
LL kuaisumi(LL x,LL n,LL mod){
    LL ans=1;
    while(n){
        if(n&1)
            ans=kuaisucheng(ans,x,mod);
        x=kuaisucheng(x,x,mod);
        ans%=mod;
        x%=mod;
        n>>=1;
    }
    return ans;
}
int main(){
    LL n,p;
    while(cin>>n>>p){
        if(n==1){
            cout<<1%p<<endl;
            continue;
        }
        LL h=kuaisumi(2,n,p);
        //cout<<h<<endl;
        cout<<((h-2)+p)%p<<endl;
    }
    return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值