1. 程式人生 > 其它 >P4781 【模板】拉格朗日插值

P4781 【模板】拉格朗日插值

\(\text{Note}\)

考慮建構函式\(f\)

\[f(k)=\sum_{i=1}^{n} y_i\prod_{j\neq i }\frac{k-x_j}{x_i-x_j} \]

求多項式在某一位置的取值

對於求\(f(k)\),將\(k\)帶入即可,時間複雜度為\(O(n^2)\)

求多項式每一項的係數

考慮將\(f\)展開,時間複雜度的瓶頸在於求\(\prod_{j\neq i }(x-x_j)\)
先預處理出\(S = \prod (x-x_j)\)
所以\(\prod_{j\neq i }(x-x_j) = \frac{S}{x - x_i}\),此時用樸素的多項式除法即可,時間複雜度仍為\(O(n^2)\)

\(\text{Code}\)

求多項式在某一位置的取值

#include<cstdio>
#define LL long long
using namespace std;
const int P = 998244353;
int n; LL m,x[2005],y[2005];

LL fpow(int x,LL y)
{
	LL res = 1;
	for (; x; x >>= 1,y = y * y % P)
		if (x & 1) res = res * y % P;
	return res;
}
int main()
{
	scanf("%d%lld",&n,&m);
	for (int i = 1; i <= n; i++) scanf("%lld%lld",&x[i],&y[i]);
	LL ans = 0;
	for (int i = 1; i <= n; i++)
	{
		LL p = y[i],q = 1;
		for (int j = 1; j <= n; j++) 
			if (j != i) p = p * (m - x[j]) % P,q = q * (x[i] - x[j]) % P;
		p = (p + P) % P,q = (q + P) % P;
		ans = (ans + p * fpow(P - 2,q) % P) % P;
	}
	printf("%lld\n",ans);
 }