3157: 国王奇遇记 & 3516: 国王奇遇记加强版 - BZOJ

时间:2024-09-01 19:35:08

果然我数学不行啊,题解君: http://www.cnblogs.com/zhuohan123/p/3726933.html

 const
h=;
var
fac,facinv,powm,s:array[..]of int64;
n,m:int64; function mexp(a,b:int64):int64;
begin
if b= then exit();
mexp:=sqr(mexp(a,b>>))mod h;
if b and = then mexp:=mexp*a mod h;
end; function C(n,r:int64):int64;
begin
exit((fac[n]*facinv[r] mod h)*facinv[n-r] mod h);
end; procedure main;
var
i,j:longint;
begin
read(n,m);
if m= then
begin
write((n*(n+)div )mod h);
exit;
end;
fac[]:=;
for i:= to m do
fac[i]:=fac[i-]*i mod h;
facinv[m]:=mexp(fac[m],h-);
facinv[]:=;
for i:=m- downto do
facinv[i]:=facinv[i+]*(i+)mod h;
powm[]:=;
for i:= to m do
powm[i]:=-powm[i-];
s[]:=((mexp(m,n+)-m+h)mod h)*mexp(m-,h-)mod h;
for i:= to m do
begin
s[i]:=mexp(n,i)*mexp(m,n+)mod h;
for j:= to i- do
s[i]:=(s[i]+powm[i-j]*(C(i,j)*s[j]mod h)+h)mod h;
s[i]:=s[i]*mexp(m-,h-)mod h;
end;
write(s[m]);
end; begin
main;
end.