Description
称一个1,2,...,N的排列P1,P2...,Pn是Magic的,当且仅当2<=i<=N时,Pi>Pi/2.计算1,2,...N的排列中有多少是Magic的,答案可能很大,只能输出模P以后的值
Input
输入文件的第一行包含两个整数 n和p,含义如上所述。
Output
输出文件中仅包含一个整数,表示计算1,2,⋯, �的排列中, Magic排列的个数模 p的值。
Sample Input
20 23
Sample Output
16
HINT
100%的数据中,1 ≤ N ≤ 10^6, P ≤ 10^9,p是一个质数。
就是求大小为n的小根堆有多少种形态
递推解决
大小为i的堆的左子堆大小为l,右子堆大小为r
那么其答案ans[i]=ans[l]*ans[r]*C(l,l+r) (C是组合数)
剩下的都是细节问题……
program bzoj2111;
var
i,j,k,n,p,l,r,o,w:longint;
ans:array [0..1000001] of longint;
function power (a,b:longint):longint;
var
ans:longint;
begin
ans:=1;
while b<>0 do
begin
if b and 1 = 1 then ans:=int64(ans)*a mod p;
b:=b div 2;
a:=int64(a)*a mod p;
end;
exit(ans);
end;
begin
read(n,p);
ans[0]:=1;
ans[1]:=1;
ans[2]:=1;
ans[3]:=2;
l:=1;
r:=1;
k:=2;
o:=2;
for i:=4 to n do
begin
k:=k*int64(l+r+1) mod p;
w:=i-(1 shl o)+1;
if w<=1 shl (o-1) then
begin
inc(l);
k:=int64(k)*power(l,p-2) mod p;
end
else
begin
inc(r);
k:=int64(k)*power(r,p-2) mod p;
end;
ans[i]:=int64(ans[l])*ans[r] mod p * k mod p;
if i=(1 shl (o+1))-1 then inc(o);
end;
writeln(ans[n]);
end.