【BZOJ 3157&&BZOJ 3516】—国王奇遇记&&加强版(扰动法+Dp)

传送门

加强版

考虑设f(i)=j=1njimjf(i)=\sum_{j=1}^nj^im^j
用扰动法化简,得到
(m1)f(i)=j=1njimj+1j=1njimj=j=1n+1(j1)imjj=1njimj=nimn+1+j=1nmjk=0i1(ik)(1)ikjk=nimn+1+k=0i1(ik)(1)ikj=1njkmj=nimn+1+k=0i1(ik)(1)ikf(k)(m - 1) * f(i) = \sum_{j=1}^n j^i * m^{j + 1} - \sum_{j=1}^n j^i * m^j \\ = \sum_{j=1}^{n + 1} (j - 1)^i * m^j - \sum_{j=1}^n j^i * m^j \\ = n^i * m^{n + 1} + \sum_{j=1}^n m^j \sum_{k = 0}^{i - 1} {i \choose k} * (-1)^{i - k} * j^k \\ = n^i * m^{n + 1} + \sum_{k = 0}^{i - 1} {i \choose k} * (-1)^{i - k} \sum_{j = 1}^n j^k * m^j \\ = n^i * m^{n + 1} + \sum_{k = 0}^{i - 1} {i \choose k} * (-1)^{i - k} * f(k)

然后O(m2)dpO(m^2)dp就完了

注意特判m=1m=1的情况

#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];
}
posted @ 2019-08-16 17:11  Stargazer_cykoi  阅读(152)  评论(0编辑  收藏  举报