【51nod 1229】 序列求和 V2(组合数学)
若就直接拉格朗日插值
否则
设
递推即可
#include<bits/stdc++.h>
using namespace std;
#define cs const
#define re register
#define pb push_back
#define pii pair<int,int>
#define ll long long
#define fi first
#define se second
#define bg begin
cs 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++;
}
inline int read(){
char ch=gc();
int res=0;bool 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;
}
inline ll readll(){
char ch=gc();
ll res=0;bool 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;
}
template<class tp>inline void chemx(tp &a,tp b){a<b?a=b:0;}
template<class tp>inline void chemn(tp &a,tp b){a>b?a=b:0;}
cs int mod=1e9+7;
inline int add(int a,int b){return (a+=b)>=mod?(a-mod):a;}
inline int dec(int a,int b){a-=b;return a+(a>>31&mod);}
inline int mul(int a,int b){static ll r;r=1ll*a*b;return (r>=mod)?(r%mod):r;}
inline void Add(int &a,int b){(a+=b)>=mod?(a-=mod):0;}
inline void Dec(int &a,int b){a-=b,a+=a>>31&mod;}
inline void Mul(int &a,int b){static ll r;r=1ll*a*b;a=(r>=mod)?(r%mod):r;}
inline int ksm(int a,int b,int res=1){for(;b;b>>=1,Mul(a,a))(b&1)&&(Mul(res,a),1);return res;}
inline int Inv(int x){return ksm(x,mod-2);}
inline int fix(int x){return (x<0)?x+mod:x;}
cs int N=2007;
int fac[N],ifac[N],iv[N];
inline void init_inv(cs int len=N-5){
iv[0]=iv[1]=fac[0]=ifac[0]=1;
for(int i=1;i<=len;i++)fac[i]=mul(fac[i-1],i);
ifac[len]=Inv(fac[len]);
for(int i=len-1;i;i--)ifac[i]=mul(ifac[i+1],i+1);
for(int i=2;i<=len;i++)iv[i]=mul(mod-mod/i,iv[mod%i]);
}
inline int C(int n,int m){
return n<m?0:mul(fac[n],mul(ifac[m],ifac[n-m]));
}
int pre[N],suf[N],f[N];
inline int calc(int *f,int n,int k){
if(k<=n)return f[k];
pre[0]=suf[n+1]=1;
for(int i=1;i<=n;i++)pre[i]=mul(pre[i-1],dec(k,i));
for(int i=n;i>=1;i--)suf[i]=mul(suf[i+1],dec(k,i));
int ret=0;
for(int i=1;i<=n;i++){
int now=mul(ifac[i-1],ifac[n-i]);if((n-i)&1)now=dec(0,now);
Mul(now,f[i]),Mul(now,mul(pre[i-1],suf[i+1]));
Add(ret,now);
}
return ret;
}
inline int solve(int n,int k){
for(int i=1;i<=k+2;i++)f[i]=add(f[i-1],ksm(i,k));
return calc(f,k+2,n);
}
int g[N];
inline int solve2(ll n,int k,ll r){
r%=mod;int t=ksm(r,(n+1)%(mod-1)),iv=Inv(r-1);
g[0]=mul(dec(t,r),iv);
for(int i=1,pw=n%mod,mt=pw;i<=k;i++,Mul(pw,mt)){
g[i]=dec(mul(t,pw),r);
for(int j=0;j<i;j++){
int now=mul(C(i,j),dec(g[j],r));
if((i-j)&1)now=mod-now;
Add(g[i],now);
}
Mul(g[i],iv);
}
return g[k];
}
int main(){
#ifdef Stargazer
freopen("lx.in","r",stdin);
#endif
int T=read();
init_inv();
while(T--){
ll n=readll(),k=read(),r=readll();
if(r==0)cout<<0<<'\n';
if(r==1)cout<<solve(n%mod,k)<<'\n';
if(r>1)cout<<solve2(n,k,r)<<'\n';
}
}