Luogu 4781 【模板】拉格朗日插值

模板题。

拉格朗日插值的精髓在于这个公式

$$f(x) = \sum_{i = 1}^{n}y_i\prod _{j \neq i}\frac{x - x_i}{x_j - x_i}$$

其中$(x_i, y_i)$是给定的$n$个点值。

代入任何一个给定的点值坐标$x_k$,都会发现这个式子等于$y_k$成立,因为对于任何$i \neq k$,后面的系数都至少有一项为$0$,而当$i == k$的时候,后面那一项一定为$1$,这样子就可以保证代进去的点值一定被满足。

因为题目中要求直接代入$x$求值,所以在算这个式子的时候直接把$x$代进去计算就可以了,时间复杂度$O(n^2)$,要不然求系数的过程相当于高斯消元,时间复杂度$O(n^3)$。

Code:

#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;

const int N = 2005;
const ll P = 998244353LL;

int n;
ll k, xi[N], yi[N];

template <typename T>
inline void read(T &X) {
    X = 0; char ch = 0; T op = 1;
    for (; ch > '9' || ch < '0'; ch = getchar())
        if (ch == '-') op = -1;
    for (; ch >= '0' && ch <= '9'; ch = getchar())
        X = (X << 3) + (X << 1) + ch - 48;
    X *= op;
}

inline ll fpow(ll x, ll y) {
    ll res = 1LL;
    for (; y > 0; y >>= 1) {
        if (y & 1) res = res * x % P;
        x = x * x % P;
    }
    return res;
}

int main() {
    read(n), read(k);
    for (int i = 1; i <= n; i++) 
        read(xi[i]), read(yi[i]);
    
    ll ans = 0LL;
    for (int i = 1; i <= n; i++) {
        ll mul1 = 1LL, mul2 = 1LL;
        for (int j = 1; j <= n; j++) {
            if (i == j) continue;
            mul1 = mul1 * ((k - xi[j] + P) % P) % P;
            mul2 = mul2 * ((xi[i] - xi[j] + P) % P) % P;
        }
        ans = (ans + yi[i] * mul1 % P * fpow(mul2, P - 2) % P) % P;
    }
    
    printf("%lld\n", ans);
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/CzxingcHen/p/10205959.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值