Miraclys

一言(ヒトコト)

P3723 [AH2017/HNOI2017]礼物

P3723 [AH2017/HNOI2017]礼物

题意

给定数列 \(a, b\) ,其中 \(b\) 数列可以循环移动,选择整数 \(c\) ,求 \(\sum\limits_{i = 1} ^{n}(a_i - b_i + c)^{2}\) 最小值

思路

\[\begin{aligned} &\sum\limits_{i = 1}^{n}(a_i-b_i+c)^{2} \\ &= \sum\limits_{i = 1}^{n}(a_i-b_i)^{2} + c^{2} + 2c(a_i-b_i) \\ &= \sum\limits_{i=1}^{n}a_{i}^{2} +b_{i}^{2}-2a_ib_i+c^{2}+2a_ic-2b_ic \\ &=\sum\limits_{i=1}^{n}a_{i}^{2}+\sum\limits_{i=1}^{n}b_{i}^{2}-2\sum\limits_{i=1}^{n}a_ib_i+nc^{2}+2c\sum\limits_{i=1}^{n}(a_i-b_i) \end{aligned} \]

其中,这个式子前面两项是确定值,后面两项是关于 \(c\) 的二次函数,求对称轴然后带入求最小值即可。

现在的任务就是求 \(\sum\limits_{i=1}^{n} a_ib_i\) 的最大值,我们先可以破环为链,\(b_{i+n} = b_i\),那么我们就不用管环了。考虑移动 \(k\) 位时的答案 \(\sum\limits_{i=1}^{n}a_{i}b_{i+k}\),这种形式非常卷积,如果我们把 \(a\) 数组翻转一下,那就成了 \(\sum\limits_{i=1}^{n}a_{n-i+1}b_{i+k}\) 下标和为定值,就可以 \(\text{FFT}\) 求卷积了,然后卷积扫完,在 \(n + 1\)\(2n\) 找最大值即可。

Code

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const double PI = acos(-1);
const int N = 5e4 + 5;
int n, m;
std::complex<double> F[N << 4], G[N << 4];

inline int read() {
	int x = 0, f = 1;
	char c = getchar();
	while (!isdigit(c)) {
		if (c == '-') f = -1;
		c = getchar();
	}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
	return x * f;
}

inline void FFT(std::complex<double> *A, int N) {
	if (N == 1) return ;
	int M = N >> 1;
	std::complex<double> A0[M], A1[M];
	for (int i = 0; i < M; ++i) {
		A0[i] = A[i << 1];
		A1[i] = A[i << 1 | 1];
	}

	FFT(A0, M), FFT(A1, M);
	std::complex<double> w = std::complex<double>(1.0, 0), W = std::complex<double>(cos(PI * 1.0 / M), sin(PI * 1.0 / M));
	for (int i = 0; i < M; ++i) {
		A[i] = A0[i] + w * A1[i];
		A[i + M] = A0[i] - w * A1[i];
		w *= W;
	}
}

int main() {

	n = read(), m = read();
	
	ll ans = 0;
	int x;
	for (int i = 1; i <= n; ++i) {
		x = read();
		ans += x * x;
		F[i] = x;
	}
	for (int i = 1; i <= n; ++i) {
		x = read();
		ans += x * x;
		G[i] = x;
	}

	int c = 0;
	for (int i = 1; i <= n; ++i) c += G[i].real() - F[i].real();
	int l1, l2;
	l1 = c / n;
	if (c <= 0) l2 = l1 - 1;
	else l2 = l1 + 1;
	int Min1 = n * l1 * l1 - 2 * l1 * c;
	int Min2 = n * l2 * l2 - 2 * l2 * c;
	ans += min(Min1, Min2);

	std::reverse(G + 1, G + n + 1);
	for (int i = n + 1; i <= 2 * n; ++i) F[i] = F[i - n];

	int sum = 3 * n, k = 1;
	while (k <= sum) k <<= 1;

	FFT(F, k), FFT(G, k);

	for (int i = 0; i <= k; ++i)
		F[i] *= G[i];
	
	std::reverse(F + 1, F + k);
	FFT(F, k);

	int Max = 0;
	for (int i = n + 1; i <= 2 * n; ++i)
		Max = max(Max, (int)(F[i].real() / k + 0.5));

	printf("%d\n", ans - Max * 2);
	system("pause");
	return 0;
}
posted @ 2023-01-12 18:46  Miraclys  阅读(22)  评论(0编辑  收藏  举报

关于本博客样式

部分创意和图片借鉴了

BNDong

的博客,在此感谢