Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 448 Accepted Submission(s): 147
Problem Description
As one of the most powerful brushes, zhx is required to give his juniors problems.
zhx thinks the problem's difficulty is . He wants to arrange these problems in a beautiful way.
zhx defines a sequence beautiful if there is an that matches two rules below:
1: are monotone decreasing or monotone increasing.
2: 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 .
Input
Multiply test cases(less than ). Seek as the end of the file.
For each case, there are two integers and separated by a space in a line. ()
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
题解:
zhx认为一个漂亮的序列{ai}下列两个条件均需满足。1:a1..ai是单调递减或者单调递增的。2:ai..an是单调递减或者单调递增的。他想你告诉他有多少种排列是漂亮的。因为答案很大,所以只需要输出答案模p之后的值。
对于整段序列单调增或减,就2种情况。
对于先增后减或先减后增:确定一个序列中的最小值(最大值),其他的要么在左边,要么在右边,有2^(n-1)*2种
而在这2^n种情况中重复计算了单调增或减得情况2次。
所以答案就是(2^n-2)%p
但是n,p都是LL型的,快速幂的时候会爆LL,不能直接快速幂,所以这里要用到快速乘法.
快速乘法其实和快速幂差不多,就是把乘号改为加号.
ps:n==1时,只有一种,特判一下.p==1时直接输出0;
答案取模时要注意一下
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
LL n,p;
LL multi(LL a,LL b){//快速乘法
LL ret=0;
while(b){
if(b&1) ret=(ret+a)%p;
a=(a+a)%p;
b>>=1;
}
return ret;
}
LL powmod(LL a,LL b){//快速幂 a^b
LL ret=1;
while(b){
if(b&1) ret=multi(ret,a)%p;
a=multi(a,a)%p;
b>>=1;
}
return ret;
}
int main(){
while(cin>>n>>p){
if(p==1){
cout<<0<<endl;
}else if(n==1){
cout<<1<<endl;
}else{
LL ans= powmod(2,n) - 2;
if(ans < 0) ans += p;
cout<< ans <<endl;
}
}
return 0;
}