2019 南昌邀请赛 B. Polynomial(lagrange插值)(模板)
题目大意
给出一个n次多项式的前n+1项,求多项式的前缀和
解题思路
先用插值求出第n+2项,再用插值求出前缀和的多项式,版题
模板自制。
AC代码
#include<bits/stdc++.h>
using namespace std;
const int mod = 9999991;
int quick_pow(int a,int b)
{
int ans=1;
while(b)
{
if(b&1) ans=1LL*a*ans%mod;
a=1LL*a*a%mod;
b>>=1;
}
return ans;
}
int inv[mod];
void getInv()
{
inv[0]=inv[1]=1;
for(int i=2;i<=1005;i++)
inv[i] = 1LL*(mod - (mod / i)) * inv[mod % i] % mod;
for (int i = 1; i <= 1005; ++i)inv[i] = 1LL*inv[i] * inv[i - 1] % mod;
}
namespace lagrange{//calculate k-degree polynomial Prefix sum of n or k_degree poly' value of n
const int maxk=1000+5;//the order of the polynomial
int coeff[maxk];int suf[maxk],bef[maxk];
int mod;
int k;
void init_sum(int k_,int f[],int mod_) //need prefix k+2' value
{
mod=mod_;
k=k_+2;
for(int i=1;i<=k;i++) coeff[i]=f[i];
coeff[0]=0;
for(int i=1;i<=k;i++) coeff[i]=(coeff[i-1]+coeff[i])%mod;
}
void init_val(int k_,int f[],int mod_) //need prefix k+1's value
{
mod=mod_;
k=k_+1;
for(int i=1;i<=k;i++) coeff[i]=f[i];
}
int calc(int n)
{
if(n==0) return 0;
if(n<=k) return coeff[n];
bef[0] = suf[0] = 1;
for (int i = 1; i <= k ; ++i) {
bef[i] = 1LL*bef[i - 1] * ((n - i) % mod) % mod;
suf[i] = 1LL*suf[i - 1] * ((n + i - k - 1) % mod) % mod;
}
int res = 0;
for (int i = 1; i <= k ; ++i) {
int s = 1LL*coeff[i] * bef[i - 1] % mod * suf[k - i ] % mod * inv[i - 1] % mod * inv[k - i] % mod;
if ((k - i) & 1)s = -s;
res += s;
res = (res % mod + mod) % mod;
}
return res;
}
}
int f[1005];
int main()
{
int t;
scanf("%d",&t);
getInv();
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n+1;i++)
{
scanf("%d",&f[i]);
}
lagrange::init_val(n,f,mod);
f[n+2]=lagrange::calc(n+2);
lagrange::init_sum(n,f,mod);
int L,R;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&L,&R);
printf("%d\n",(lagrange::calc(R+1)-lagrange::calc(L)+mod)%mod);
}
}
}