HDU 5187 zhx's conte

zhx's contest

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


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
 


其实是个水题 但是wa了三次。。
题目意思是有n个数 1-n
问你有多少排列满足以下条件
存在一个i
使得a1,a2,a3,...,ai单调递增或者单调递减
且使得ai,ai+1,ai+2,...,an单调递增或者单调递减

不考虑ai=i和ai=n-i+1的情况时
首先想 先增后减 肯定n在中间
n的位置前面可以有1到n-2个数 这些数从小到大排列 n后面有n-2到1个数 从大到小排列 共(2^(n-1)-2)种情况

先减后增 同理 也是(2^(n-1)-2)种情况
加上从1到n 和 从n到1 两种情况 一共2^n-2种
所以快速幂就可以了

但是注意mod值太大 可能乘法爆long long!
所以还要用快速乘法!

值得注意的是
最后要先加mod 在%mod
因为2^n %mod可能=0
-2就是负数了


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
using namespace std;
long long m,mod;

long long xx(long long x,long long y)
{
    long long ret=0;
    while(y)
    {
        if(y&1)
            ret=(ret+x)%mod;
        x=(x+x)%mod;
        y/=2;
    }
    return ret;
}

long long quick(long long x,long long y)    //x^y %mod
{
    long long ret=1;
    while(y)
    {
        if((y&1)==1)
            ret=(xx(ret,x))%mod;
        x=(xx(x,x))%mod;
        y/=2;
    }
    return ret%mod;
}
int main()
{
    while(cin>>m>>mod)
    {
        if(m==1)
            cout<<1%mod<<endl;
        else
            cout<<((long long)quick(2,m)-2+mod)%mod<<endl;
    }
    return 0;
}



 

posted @ 2015-10-22 19:54  abgnwl  阅读(86)  评论(0编辑  收藏  举报