【模板】 拉格朗日插值
阿新 • • 發佈:2020-08-10
由n + 1 個點可以確定一個n次多項式。
拉格朗日插值法可以在 n^2 複雜度確定一個多項式並進行求解。
模板 ;
給定n 個點,以及k ,求出確定的多項式的 f(k)。
#pragma warning(disable:4996) #include<iostream> #include<algorithm> //#include<bitset> //#/include<tuple> //#include<unordered_map> #include<fstream> #include<iomanip> #include<string> #include<cmath> #include<cstring> #include<vector> #include<map> #include<set> #include<list> #include<queue> #include<stack> #include<sstream> #include<cstdio> #include<ctime> #include<cstdlib> #include <assert.h> #definepb push_back #define INF 0x3F3F3F3F #define inf 998244353 #define moD 1000000003 #define pii pair<int,int> #define eps 1e-6 #define equals(a,b) (fabs(a-b)<eps) #define bug puts("bug") #define re register #define fi first #define se second typedef long long ll; typedef unsigned long long ull; constll MOD = 998244353; const ll Mod = 998244352; const int maxn = 2e5 + 5; const double Inf = 10000.0; const double PI = acos(-1.0); using namespace std; ll mul(ll a, ll b, ll m) { ll res = 0; while (b) { if (b & 1) res = (res + a) % m; a = (a + a) % m; b >>= 1; } return res % m; } ll quickPower(ll a, ll b, ll m) { ll base = a; ll ans = 1ll; while (b) { if (b & 1) ans = mul(ans, base, m); base = mul(base, base, m); b >>= 1; } return ans; } ll ksm(ll a, ll b, ll m) { ll base = a; ll ans = 1ll; while (b) { if (b & 1) ans *= base, ans %= m; base *= base, base %= m; b >>= 1; } return ans; } ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll Lcm(ll a, ll b) { return a / gcd(a, b) * b; } int readint() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } ll readll() { ll x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } ull readull() { ull x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } void Put(ll x) { if (x < 0) putchar('-'), x *= -1; if (x > 9) Put(x / 10); putchar(x % 10 + '0'); } ll x[2005]; ll y[2005]; int main() { int n = readint(); ll k = readll(); ll res = 0; for (int i = 0; i < n; i++) x[i] = readll(), y[i] = readll(); for (int i = 0; i < n; i++) { ll tmp1 = 1ll; ll tmp2 = 1ll; for (int j = 0; j < n; j++) { if (i == j) continue; tmp1 = tmp1 * (k - x[j]) % MOD; tmp2 = (tmp2 * (((x[i] - x[j]) + MOD) % MOD)) % MOD; } res = res + y[i] * tmp1 % MOD * ksm(tmp2, MOD - 2, MOD) % MOD; res = (res + MOD) % MOD; } Put(res); }