拉格朗日插值模板题 luoguP4871

学习博客

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<queue>
#include<vector>
#include<string>
#include<fstream>

using namespace std;
typedef long long ll;
const int N = 4e6 + 105;
const int mod = 998244353;
const double Pi = acos(- 1.0);
const int INF = 0x3f3f3f3f;

int n, k;
int x[N], y[N];

int sub(const int& a, const int& b){
	int t = a - b;
	return t < 0 ? t + mod : t;
}


int inv(int x){
	int res = 1;
	int p = mod - 2;
	for(; p; p >>= 1, x = 1ll * x * x % mod)
		if(p & 1) res = 1ll * res * x % mod;
	return res;
}


int Lagrange(int n, int x[], int y[], int k){
	int res = 0;
	for(int i = 1; i <= n; ++ i){
		int s1 = 1, s2 = 1;	//s1:分子,s2:分母
		for(int j = 1; j <= n; ++ j){
			if(i != j){
				s1 = 1ll * s1 * sub(k, x[j]) % mod;
				s2 = 1ll * s2 * sub(x[i], x[j]) % mod;
			}
		}
		res = (res + 1ll * y[i] * s1 % mod * inv(s2) % mod) % mod; 
	}
	return res;
}

int main()
{
	scanf("%d%d",&n,&k);
	for(int i = 1; i <= n; ++ i) scanf("%d%d",&x[i],&y[i]);
	printf("%d\n", Lagrange(n, x, y, k));
	return 0;
}

上一篇:#特征方程,光速幂#洛谷 5110 块速递推


下一篇:C - Longge's problem