[模板] 拉格朗日插值
[题目链接]
https://www.luogu.org/problemnew/show/P4781
[算法]
拉格朗日插值即可
时间复杂度 : O(N ^ 2)
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXN 2010 const int P = 998244353; typedef long long ll; typedef long double ld; typedef unsigned long long ull; int n , k; int X[MAXN] , Y[MAXN]; template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); } template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); } template <typename T> inline void read(T &x) { T f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } inline int exp_mod(int a , int n) { int res = 1 , b = a; while (n > 0) { if (n & 1) res = 1ll * res * b % P; b = 1ll * b * b % P; n >>= 1; } return res; } inline int inv(int x) { return exp_mod(x , P - 2); } inline void update(int &x , int y) { x = (x + y) % P; if (x < 0) x += P; } inline int Lagrange(int x) { int ret = 0; for (int i = 1; i <= n; i++) { int value = Y[i]; for (int j = 1; j <= n; j++) { if (i != j) value = 1ll * value * (x - X[j]) % P * inv(((X[i] - X[j]) % P + P) % P) % P; } update(ret , value); } return ret; } int main() { read(n); read(k); for (int i = 1; i <= n; i++) { read(X[i]); read(Y[i]); } printf("%d\n" , Lagrange(k)); return 0; }