[bzoj5339][TJOI2018]教科书般的亵渎【拉格朗日插值法】

【题目链接】
  https://www.lydsy.com/JudgeOnline/problem.php?id=5339
  https://loj.ac/problem/2578
【题解】
  显然 k = m + 1 k=m+1 k=m+1,然后就是一个 k k k次幂的前缀和减去几个没有的值。
  用插值法可以实现。
  时间复杂度 O ( M 3 ) O(M^3) O(M3)
【代码】

# include 
# define 	ll 		long long
# define 	inf 	0x3f3f3f3f
# define 	N 		110
using namespace std;
int read(){
	int tmp = 0, fh = 1; char ch = getchar();
	while (ch < '0' || ch > '9') {if (ch == '-') fh = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9'){tmp = tmp * 10 + ch - '0'; ch = getchar(); }
	return tmp * fh;
}
ll readll(){
	ll tmp = 0, fh = 1; char ch = getchar();
	while (ch < '0' || ch > '9') {if (ch == '-') fh = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9'){tmp = tmp * 10 + ch - '0'; ch = getchar(); }
	return tmp * fh;
}
const int P = 1e9 + 7;
ll num[N], n;
int m, x[N], y[N];
int power(int x, int y){
	int i = x; x = 1;
	while (y > 0){
		if (y % 2 == 1) x = 1ll * x * i % P;
		i = 1ll * i * i % P;
		y /= 2;
	}
	return x;
}
int getsum(ll tmp, int lim){
	int sum = 0; tmp %= P;
	for (int i = 1; i <= lim; i++){
		int num1 = 1, num2 = 1;
		for (int j = 1; j <= lim; j++)
			if (i != j){
				num1 = 1ll * num1 * (tmp - x[j]) % P;
				num2 = 1ll * num2 * (x[i] - x[j]) % P;
			}
		sum = (sum + 1ll * num1 * y[i] % P * power(num2, P - 2)) % P;
	}
	return sum;
}
int main(){
//	freopen(".in", "r", stdin);
//	freopen(".out", "w", stdout);
	for (int opt = read(); opt--;){
		n = readll(), m = read();
		for (int i = 1; i <= m; i++)
			num[i] = readll();
		sort(num + 1, num + m + 1);
		int k = m + 1;
		for (int i = 1; i <= k + 2; i++)
			x[i] = i, y[i] = (y[i - 1] + power(i, k)) % P; 
		int ans = 0;
		for (int i = 1; i <= k; i++){
			ll now = n - num[i - 1];
			ans = (ans + getsum(now, k + 2)) % P;
			for (int j = i; j <= m; j++)
				ans = (ans - power(num[j] - num[i - 1], k)) % P;
		}
		printf("%d\n", (ans + P) % P);
	}
	return 0;
}

你可能感兴趣的:(【拉格朗日插值法】)