bestcoder#33 1002 快速幂取余+模拟乘,组合数学

bestcoder#33 1002 快速幂取余+模拟乘,组合数学

zhx's contest


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


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
 
题意:对于数列an(1-n),使a1..ai...an,先单增后单减,或先单减后单增,或直接单调,问合法数列的个数,答案取余
尝试可知,设i为最值m在an的位置,则在第i个位置满足情况的有c(n-1,i)(i==0||i==n-1)或2*c(n-1,ii)(0<i<n-1)种,故ans=2*(c(n-1,0)+c(n-1,1)+...c(n-1,n-1))-2=2^n-2,由于数据会爆long long ,所以每次取余,用快速幂+模拟乘法,在模拟乘法中取余
//bestcoder#33 1002
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>

using namespace std;

const long long INF=(1LL<<62);
long long n,p;

long long multi(long long a,long long b,long long MOD)//模拟乘法,a*b=a+a+a+...+a(b个a相加) 方法用分治,和快速幂相同
{
    long long res=0;
    while(b){
        if(b&1) res=(res+a)%MOD;
        a=(2*a)%MOD;
        b=b>>1;
    }
    return res;
}

long long quickpow(long long n,long long k,long long MOD)
{
    long long res=1;
    while(k){
        if(k&1) res=multi(res,n,MOD);//直接乘会越界,需要模拟在模拟过程中取余数
        n=multi(n,n,MOD);
        k=k>>1; //也就是K/=2,位运算更快
    }
    return res;
}

int main()
{
    while(cin>>n>>p){
        if(n==1) cout<<1%p<<endl;
        else cout<<(quickpow(2,n,p)-2+p)%p<<endl;
    }
    return 0;
}
bestcoder#33 1002

 

posted @ 2015-03-15 10:31  __560  阅读(223)  评论(0编辑  收藏  举报