洛谷P4781 【模板】拉格朗日插值(拉格朗日插值)

自為風月馬前卒發表於2018-12-01

題意

題目連結

Sol

記得NJU有個特別強的ACM隊叫拉格朗,總感覺少了什麼。。

不說了直接扔公式

[f(x) = sum_{i = 1}^n y_i prod_{j
ot = i} frac{k – x[j]}{x[i] – x[j]}]

複雜度(O(n^2))

如果(x)的取值是連續的話就字首積安排一下,複雜度(O(n))

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 10, mod = 998244353;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < `0` || c > `9`) {if(c == `-`) f = -1; c = getchar();}
    while(c >= `0` && c <= `9`) x = x * 10 + c - `0`, c = getchar();
    return x * f;
}
int N, K, x[MAXN], y[MAXN];
int add(int x, int y) {
    if(x + y < 0) return x + y + mod;
    return x + y >= mod ? x + y - mod : x + y;
}
int mul(int x, int y) {
    return 1ll * x * y % mod;
}
int fp(int a, int p) {
    int base = 1;
    while(p) {
        if(p & 1) base = mul(base, a);
        a = mul(a, a); p >>= 1;
    }
    return base;
}
int Lagelangfuckchazhi(int k) {
    int ans = 0;
    for(int i = 1; i <= N; i++) {
        int up = 1, down = 1;
        for(int j = 1; j <= N; j++) {
            if(i == j) continue;
            up = mul(up, add(k, -x[j]));
            down = mul(down, add(x[i], -x[j]));
        }
        ans = add(ans, mul(y[i], mul(up, fp(down, mod - 2))));
    }
    return ans;
}
int main() {
    N = read(); K = read();
    for(int i = 1; i <= N; i++) x[i] = read(), y[i] = read();
    printf("%d", Lagelangfuckchazhi(K));
    return 0;
}
/*
*/

相關文章