跳到正文

题解

题解:P11671 [USACO25JAN] Farmer John's Favorite Operation S

Felix72约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年2月11日
收录
2026年5月28日
更新
2026年11月13日
篇幅
约 2 分钟
题目
P11671

版本

  1. v1当前

我居然这个题上还想了一会,可能是数据结构题做多导致思维钝化了?

由于模意义下数轴是个环,因此问题几何意义如下:

在长度为 mm 的环上给定 nn 个点,选出点 xx 使得每个点离 xx 的距离和最小。

这个问题在链上可以直接取中位下标,在环上先枚举断一条边就转化为链上问题了。前缀和拆贡献。

C++
/* Good Game, Well Play. */
#include <bits/stdc++.h>
#define lowbit(x) ((x) & (-(x)))
using namespace std;

const int N = 200010;
int T, n, m;
long long pr_a[N * 2], a[N * 2];
inline void sol()
{
	cin >> n >> m; long long res = 1e18;
	for(int i = 1; i <= n; ++i) cin >> a[i], a[i] %= m;
	sort(a + 1, a + n + 1);
	for(int i = 1; i <= n; ++i) a[i + n] = a[i] + m;
	for(int i = 1; i <= 2 * n; ++i) pr_a[i] = pr_a[i - 1] + a[i];
	for(int l = 1; l <= n; ++l)
	{
		int r = l + n - 1, mid = (l + r) >> 1;
		res = min(res, (mid - l + 1) * a[mid] - (pr_a[mid] - pr_a[l - 1]) + (pr_a[r] - pr_a[mid]) - (r - mid) * a[mid]);
	}
	cout << res << '\n';
}

int main()
{
//	freopen("text.in", "r", stdin);
//	freopen("prog.out", "w", stdout);
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> T;
	while(T--) sol();
	return 0;
}
/*

*/
原文
存档评论1 条抓取于