【CodeForces - 622F 】The Sum of the k-th Powers (拉格朗日插值)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Coldfresh/article/details/81908484

这里写图片描述

Examples
Input
4 1
Output
10
Input
4 2
Output
30
Input
4 3
Output
100
Input
4 0
Output
4
这个就直接上我的模板就可以了.

#include<iostream>
#include<cstdio>
#include<cmath>
#define ll long long
#define maxn 1000005
#define mod 1000000007
using namespace std;
ll f[maxn];
ll fac[maxn],inv[maxn];
ll P(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1)ans=ans*a%mod;
        b>>=1;
        a=a*a%mod;
    }
    if(ans<0)ans+=mod;
    return ans;
}
void init(int tot)
{
    fac[0]=1;
    for(int i=1;i<=tot;i++)
        fac[i]=fac[i-1]*i%mod;
    inv[tot]=P(fac[tot],mod-2);
    inv[0]=1;
    for(int i=tot-1;i>=1;i--)
        inv[i]=inv[i+1]*(i+1)%mod;
}
ll Lagrange(ll n,ll k)
{
    int tot=k+1;
    init(tot);
    ll ans=0;
    ll now=1;
    for(int i=1;i<=tot;i++)
            now=now*(n-i)%mod;
    for(int i=1;i<=tot;i++)
    {
        ll inv1=P(n-i,mod-2);
        ll inv2=inv[i-1]*inv[tot-i]%mod;
        if((tot-i)&1)
            inv2=mod-inv2;
        ll temp=now*inv1%mod;
        temp=temp*f[i]%mod*inv2%mod;
        ans+=temp;
        if(ans>=mod)ans-=mod;
    }
    return ans;
}
int main()
{
    ll n,k;
    cin>>n>>k;
    for(int i=1;i<=k+2;i++)
        f[i]=(f[i-1]+P(i,k))%mod;
    if(n<=k+2)
        cout<<f[n]<<endl;
    else
        cout<<Lagrange(n,k+1)<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Coldfresh/article/details/81908484