【模板】拉格朗日插值

拉格朗日插值的公式大概是

\(f(k) = \sum_{i=0}^{n}y_i \prod_{j!=i} \frac{k-x_j}{x_i-x_j}\)

\(x_i,y_i\) 是在 \(x_i\) 的取值。

#include <bits/stdc++.h>
#define int long long
using namespace std;
struct io {
	char buf[1 << 26 | 3], *s; int f;
	io() { f = 0, buf[fread(s = buf, 1, 1 << 26, stdin)] = '\n'; }
	io& operator >> (int&x) {
		for(x = f = 0; !isdigit(*s); ++s) f |= *s  == '-';
		while(isdigit(*s)) x = x * 10 + (*s++ ^ 48);
		return x = f ? -x : x, *this;
	}
};

const int mod = 998244353;
int qpow(int x, int y) {
  int res = 1;
  for(; y; y >>= 1, x = x * x % mod)
    if(y & 1) res = res * x % mod;
  return res;
}
int inv(int x) { return qpow(x, mod - 2); }

int n, k;
const int maxn  = 2e3 + 32;
int x[maxn], y[maxn];

#define out cout
signed main() {
#ifdef LOCAL
#define in cin
  ios :: sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  freopen("testdata.in", "r", stdin);
#else
  io in;
#endif
  in >> n >> k;
  for(int i = 1 ; i <= n ; i ++) in >> x[i] >> y[i];
  int ans = 0;
  for(int i = 1 ; i <= n ; i ++) {
    int a, b; a = b = 1;
    for(int j = 1 ; j <= n ; j ++) if(i ^ j) { a = a * (k - x[j]) % mod; }
    for(int j = 1 ; j <= n ; j ++) if(i ^ j) { b = b * (x[i] - x[j]) % mod; }
    a = (a + mod) % mod, b = (b + mod) % mod, b = inv(b);
    ans = (ans + a * b % mod * y[i] % mod) % mod;
  }
  out << ans << '\n';
  return 0;
}
posted @ 2020-05-02 18:14  _Isaunoya  阅读(158)  评论(0编辑  收藏  举报