【BZOJ 3157&&BZOJ 3516】—国王奇遇记&&加强版(扰动法+Dp)
考虑设,
用扰动法化简,得到
然后就完了
注意特判的情况
#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ib==ob)?EOF:*ib++;
}
#define gc getchar
inline int read(){
char ch=gc();
int res=0,f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
#define re register
#define pb push_back
#define cs const
#define pii pair<int,int>
#define fi first
#define se second
#define ll long long
#define poly vector<int>
#define bg begin
cs int mod=1e9+7;
inline int add(int a,int b){return (a+=b)>=mod?a-mod:a;}
inline void Add(int &a,int b){(a+=b)>=mod?(a-=mod):0;}
inline int dec(int a,int b){return (a-=b)<0?a+mod:a;}
inline void Dec(int &a,int b){(a-=b)<0?(a+=mod):0;}
inline int mul(int a,int b){return 1ll*a*b>=mod?1ll*a*b%mod:a*b;}
inline void Mul(int &a,int b){a=mul(a,b);}
inline int ksm(int a,int b,int res=1){
for(;b;b>>=1,a=mul(a,a))(b&1)&&(res=mul(res,a));return res;
}
inline void chemx(int &a,int b){a<b?a=b:0;}
inline void chemn(int &a,int b){a>b?a=b:0;}
cs int N=1006;
int fac[N],ifac[N];
inline void init(cs int len=N-5){
fac[0]=ifac[0]=1;
for(int i=1;i<=len;i++)fac[i]=mul(fac[i-1],i);
ifac[len]=ksm(fac[len],mod-2);
for(int i=len-1;i;i--)ifac[i]=mul(ifac[i+1],i+1);
}
inline int C(int n,int m){
if(n<m)return 0;
return mul(fac[n],mul(ifac[m],ifac[n-m]));
}
int n,m;
int f[N],pt[N];
int main(){
init(),n=read(),m=read();
if(m==1){cout<<(1ll*(n+1)*n/2)%mod;return 0;}
pt[0]=1;int mt=ksm(m,n+1),inv=ksm(m-1,mod-2);
for(int i=1;i<N;i++)pt[i]=mul(pt[i-1],n);
f[0]=mul(dec(mt,m),inv);
for(int i=1;i<=m;i++){
int res=0;
for(int k=0;k<=i-1;k++)
if((i-k)&1)Dec(res,mul(f[k],C(i,k)));
else Add(res,mul(f[k],C(i,k)));
Add(res,mul(pt[i],mt));
f[i]=mul(res,inv);
}
cout<<f[m];
}