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

· · 题解

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

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

在长度为 m 的环上给定 n 个点,选出点 x 使得每个点离 x 的距离和最小。

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

/* 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;
}
/*

*/