zhx's contest
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 575 Accepted Submission(s): 181
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
.
). 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. (1≤n,p≤1018
)
3 5
1
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
1002 zhx and contest
如果n=1 ,答案是1 ,否则答案是2 n −2 。
证明:a i 肯定是最小的或者最大的。考虑另外的数,如果它们的位置定了的话,那么整个序列是唯一的。
那么a i 是最小或者最大分别有2 n−1 种情况,而整个序列单调增或者单调减的情况被算了2次,所以要减2。
要注意的一点是因为p>2 31 ,所以要用快速乘法。用法与快速幂相同。如果直接乘会超过long long范围,从而wa掉。
13127194 | 2015-03-14 22:34:13 | Accepted | 5187 | 109MS | 1664K | 1179 B | G++ | czy |
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <string> #define ll long long
int const N = ;
int const M = ;
int const inf = ;
ll const mod = ; using namespace std; ll n,p;
ll ans; ll quickmul(ll x,ll m)
{
ll re=;
while(m){
if(m&){
re=(re+x)%p;
}
m/=;
x=(x+x)%p;
}
return re;
} ll quickpow(ll x,ll m)
{
ll re=;
while(m)
{
if(m&){
re=quickmul(re,x);
}
m/=;
x=quickmul(x,x);
}
return re;
} void ini()
{ } void solve()
{
if(n==){
if(p!=)
ans=;
else
ans=;
return;
}
else{
ans=quickpow(2LL,n)-2LL;
ans=(ans+p)%p;
}
} void out()
{
printf("%I64d\n",ans);
} int main()
{
//freopen("data.in","r",stdin);
//scanf("%d",&T);
//for(cnt=1;cnt<=T;cnt++)
while(scanf("%I64d%I64d",&n,&p)!=EOF)
{
ini();
solve();
out();
}
}
再贴一发Java的程序:
13131089 | 2015-03-15 10:47:30 | Accepted | 5187 | 421MS | 9640K | 858 B | Java | czy |
//import java.io.*;
import java.util.*;
import java.math.*; public class Main {
static BigInteger quickpow (BigInteger x, long m, BigInteger p )
{
BigInteger re = BigInteger.ONE;
while(m >= 1)
{
if(m % 2 == 1){
re = re.multiply(x).mod(p);
}
x = x.multiply(x).mod(p);
m = m / 2;
}
return re;
} public static void main(String[] args){
Scanner in = new Scanner(System.in);
long n;
BigInteger p;
BigInteger ans;
while(in.hasNext())
{
n = in.nextLong();
p = in.nextBigInteger();
if(n == 1){
if(p.equals(BigInteger.ONE)){
ans = BigInteger.ZERO;
}
else{
ans = BigInteger.ONE;
}
}
else{
ans = quickpow(BigInteger.valueOf(2),n,p).subtract(BigInteger.valueOf(2));
ans = ans.add(p).mod(p);
}
System.out.println(ans);
}
}
}