视频链接:
The Sum of the k-th Powers - 洛谷 | 计算机科学教育新生态
// 拉插 O(klogn) #include <iostream> #include <cstring> #include <algorithm> using namespace std;#define LL long long const int N=1e6+10,mod=1e9+7; int n,k; LL ml[N],mr[N],fac[N],y,a,b,ans;LL ksm(LL a,LL b){LL s=1;while(b){if(b&1)s=s*a%mod;a=a*a%mod;b>>=1;}return s; } int main(){scanf("%d%d",&n,&k);ml[0]=mr[k+3]=fac[0]=1;for(int i=1;i<=k+2;i++)ml[i]=ml[i-1]*(n-i)%mod; //前缀积for(int i=k+2;i>=1;i--)mr[i]=mr[i+1]*(n-i)%mod; //后缀积for(int i=1;i<=k+2;i++)fac[i]=fac[i-1]*i%mod; //阶乘for(int i=1;i<=k+2;i++){y=(y+ksm(i,k))%mod;a=ml[i-1]*mr[i+1]%mod;b=fac[i-1]*fac[k+2-i]*((k+2-i)&1?-1:1)%mod;ans=(ans+y*a%mod*ksm(b,mod-2)%mod)%mod;}printf("%d\n",(ans+mod)%mod); }