[HDU 5187][组合数求和][快速幂+乘]zhx's contest

题目描述:
题目链接:HDU 5187 zhx’s contest
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
题目大意:给你数字n,将1~n进行排列,求有多少种排列方式使得存在 ai ,令此排列 a1..ai 单调递增或单调递减且 ai..an 单调递增或单调递减。最后答案模p。
PS:多组输入数据,每行一组,两个数字n,p。数据范围: 1n,p1018
题目分析:
由题知,存在四种情况:单调递减,单调递增,单调递增再单调递减(顶点为n),单调递减再单调递增(顶点为1)。
考虑后两种情况,以n为例,假设n左边有x个数,右边则有(n-1)-x个数。无论这x个数是哪些,它们必然都能排成唯一情况的一个单调递增的序列,而(n-1)-x个数也能排成唯一情况的一个单调递减的序列。当我左边确定后,右边也随之确定。考虑左边,其实就是从n-1个数选x个数,方案数 Cxn1 ,所以对于顶点n总的方案数就是sum= C0n1 + C1n1 + C2n1 +······+ Cn1n1 ( C0n1 就是单调递减, Cn1n1 就是单调递增的情况),对于顶点1一样,于是 ans=2sum ,但你单调递减、单调递增多算了一遍,于是 ans=2sum2 。考虑求sum,其实组合数求和有公式: C0n + C1n + C2n +······+ Cnn = 2n 。于是sum= 2n1 ,ans= 2n -2。看一下数据范围,于是就是快速幂+快速乘。
PS:公式证明:我们知道组合数和多项式展开的系数都是对应杨辉三角的,也就是说组合数和多项式展开的系数式是对应的。即: a+bn=C0nan+C1nan1b+C2nan2b2++Cnnbn ,于是把a,b都代成1就有上面的公式了。
附代码:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<cmath>
#include<cctype>
#include<iomanip>
#include<algorithm>
using namespace std;

long long n,p,ans;

long long ksc(long long x,long long y)
{
    long long ret=0;
    for(;y;y>>=1,x=(x+x)%p)
        if(y&1) ret=(ret+x)%p;
    return ret;
}

long long ksm(long long x,long long y)
{
    long long ret=1;
    for(;y;y>>=1,x=(ksc(x,x)))
        if(y&1) ret=ksc(ret,x);
    return ret;
}

int main()
{
    //freopen("lx.in","r",stdin);

    while(scanf("%I64d%I64d",&n,&p)!=EOF)
    {
        ans=(ksm(2,n)+p-2)%p;//这里要加p再减2,否则如果你得到一个小于2的数,你的答案就会是负数
        printf("%I64d\n",ans);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值