HDU 5187 zhx's contest(思维,快速幂,快速乘)

zhx's contest

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


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
 

Recommend

hujie



这题我们可以借助DP的思想推出公式, [ 1 ~ N ] 所有满足条件的排列就等于 [ 1 ~ N -1 ] 所有满足条件的排列插进去一个 N,其中单调递增和单调递减排列我们可以将N插进三个位置          例如:  原排列为 [ 1 , 2 , 3 ] ,我们可以将4插入将其修改成 [ 1 , 2 , 3 , 4] 、[ 1 , 2 , 4 , 3]、[ 4 , 1 , 2, 3 ],而增减序列和减增序列只能将N插入两个位置  ( [ 1 , 3 , 2 ]  改为 [ 1 , 3 , 4 ,2]、[ 1 , 4 , 3 , 2] ),显而易见状态转移方程为dp[ i ] = dp[ i - 1 ] * 2 + 2

然而这题的数据范围太大,并不允许我们dp求解,但我们可以借助dp打表推公式。。。。


显而易见公式为 2 ^ n -2,然而这题数据范围太大,直接用快速幂会爆 long long ,所以还需加一步快速乘。

PS:数学不好真心伤不起啊。。忙活半天才把公式找出来。。。。。。。


#include<bits/stdc++.h>
using namespace std;
long long n,Mod;
long long mul(long long a,long long b)
{
    long long res=0;
    while(b)
    {
        if(b&1) res=(a+res)%Mod;
        b>>=1;
        a=(a+a)%Mod;
    }
    return res;
}
long long xx(long long a,long long n)
{
    long long ret=1;
    long long tmp=a%Mod;
    while(n)
    {
        if(n&1)
            ret=mul(ret,tmp)%Mod;
        tmp=mul(tmp,tmp)%Mod;
        n>>=1;
    }
    return ret;
}
int main()
{
    while(scanf("%I64d%I64d",&n,&Mod)==2)
    {
        printf("%I64d\n",(xx(2,n)%Mod-2+Mod)%Mod);  ///2^n-2可能为负数,所以要加一个Mod
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值