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

2018-12-21 16:57:00 浏览数 (1)

题意

题目链接

Sol

记得NJU有个特别强的ACM队叫拉格朗,总感觉少了什么。。

不说了直接扔公式

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

复杂度(O(n^2))

如果(x)的取值是连续的话就前缀积安排一下,复杂度(O(n))

代码语言:javascript复制
#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;
}
/*
*/

0 人点赞