HDU 5187 zhx's contest(组合数学)

来源:互联网 发布:免费动漫下载软件 编辑:程序博客网 时间:2024/05/17 02:41

传送门

zhx’s contest

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


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
 

题目大意:

作为史上最强的刷子之一,zhx的老师让他给学弟(mei)们出n道题。
zhx认为第i道题的难度就是i。他想要让这些题目排列起来很漂亮。
zhx认为一个漂亮的序列{ai}下列两个条件均需满足
1:a1..ai是单调递减或者单调递增的。
2:ai..an是单调递减或者单调递增的。
他想你告诉他有多少种排列是漂亮的。
因为答案很大,所以只需要输出答案模p之后的值。

解题思路:

首先我们将题目给定的条件在细化一下:
(1)a1..ai是单调递增的,那么ai..an一定是单调递减的,而且 ai=n
(2)a1..ai是单调递减的,那么ai..an一定是单调递增的,而且 ai=1
将条件细化成这样之后就好想多了,其实 (1)(2) 是没有什么区别的,就拿第一个来说,因为 ai=n 这是确定的,所以只需要确定 i 的位置就行啦,确定好 i 的位置之后,剩下的就是简单的组合数学了,假设 n=5,那么 i 的位置有 5 个,刨除掉 1,还有 4 个数
i=1C04
i=2C14
i=3C24
i=4C34
i=5C44
所以总数是 24 根据二项式定理,那么满足第 (2) 个条件的也有 24 个,但是中间有重复的,就是单调递增的和单调递减的多算了以此,所以减 2,总数就是 2422,可以推出这个题的总的方法数就是 2n122, 即 2n2,还需要注意的问题就是,这个取模的数太大,所以在进行快速幂的时候不要直接乘,要进行快速乘法。

MyCode

#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>using namespace std;typedef long long LL;LL n, MOD;LL Multi_mod(LL a, LL b){    LL ans = 0;    while(b){        if(b & 1LL)            ans = (ans + a) % MOD;        b>>=1LL;        a = (a + a) % MOD;    }    return ans;}LL Pow_mod(LL a, LL b){    LL ans = 1LL;    a %= MOD;    while(b){        if(b & 1LL)            ans = Multi_mod(ans, a);        b>>=1LL;        a = Multi_mod(a, a);    }    ans = (ans-2LL) % MOD;    ans = (ans % MOD + MOD) % MOD;    return ans;}int main(){    while(~scanf("%lld%lld",&n,&MOD)){        if(n == 1LL){            if(MOD == 1)                puts("0");            else                puts("1");            continue;        }        printf("%lld\n",Pow_mod(2LL, n));    }}
0 0
原创粉丝点击