Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

拉格朗日插值模板

已知 $n$ 个点,快速确定一个 $n - 1$ 次多项式。

求 $f(x)$ 。

$$
f(x)=\sum_{i=1}^n{y_i\prod_{j\ne i}{\dfrac {x-x_j}{x_i-x_j}}}
$$

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <cstdio>
#include <utility>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 2e3 + 10, mod = 998244353;
PII p[N];
int n, k;
LL binpow(LL b, int k)
{
LL res = 1;
while (k)
{
if (k & 1)
res = res * b % mod;
b = b * b % mod;
k >>= 1;
}
return res;
}
int main()
{
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++)
scanf("%d%d", &p[i].first, &p[i].second);
LL res = 0;
for (int i = 1; i <= n; i++)
{
LL s = p[i].second;
for (int j = 1; j <= n; j++)
if (i != j)
s = s * (k - p[j].first) % mod * binpow(p[i].first - p[j].first, mod - 2) % mod;
res = (res + s) % mod;
}
printf("%lld", (res % mod + mod) % mod);
return 0;
}