拉格朗日插值的模板。
//Achen
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<cstdio>
#include<queue>
#include<cmath>
const int mod=1e9+7,N=5e4+7;
typedef long long LL;
using namespace std;
int T,k;
LL n,sum[N],up,dn,fac[N],ans,inv[N],p[N],q[N];
template<typename T>void read(T &x) {
char ch=getchar(); x=0; T f=1;
while(ch!=‘-‘&&(ch<‘0‘||ch>‘9‘)) ch=getchar();
if(ch==‘-‘) f=-1,ch=getchar();
for(;ch>=‘0‘&&ch<=‘9‘;ch=getchar()) x=x*10+ch-‘0‘; x*=f;
}
LL ksm(LL a,LL b) {
LL base=a,res=1;
while(b) {
if(b&1) res=res*base%mod;
base=base*base%mod;
b>>=1;
}
return res;
}
int main() {
read(T);
fac[0]=1;
for(int i=1;i<=50002;i++) fac[i]=fac[i-1]*i%mod;
inv[1]=1;
for(int i=2;i<=50002;i++) inv[i]=(mod-mod/i*inv[mod%i]%mod)%mod;
while(T--) {
read(n); read(k); k++; up=1; ans=0;
for(int i=1;i<=k+1;i++) sum[i]=(sum[i-1]+ksm(i,k-1))%mod;
if(n<=k+1) printf("%lld\n",sum[n]);
else {
n%=mod; p[0]=q[k+2]=1;
dn=ksm(((k&1)?(mod-fac[k])%mod:fac[k]),mod-2);
for(int i=1;i<=k+1;i++) p[i]=(p[i-1]*(n-i)%mod+mod)%mod;
for(int i=k+1;i>=1;i--) q[i]=(q[i+1]*(n-i)%mod+mod)%mod;
for(int i=1;i<=k+1;i++) {
LL upi=p[i-1]*q[i+1]%mod;
ans=(ans+upi*dn%mod*sum[i]%mod)%mod;
dn=(mod-dn*(k-i+1)%mod*inv[i]%mod)%mod;
}
printf("%lld\n",ans);
}
}
return 0;
}
/*
1
4 1
*/