HDU25.8.8 1002 龙族栖息地 题解

· · 题解

https://acm.hdu.edu.cn/contest/problem?cid=1178&pid=1002

Solution

设龙穴在 (x,y,z),第 i 条龙在 (a_i,b_i,c_i)。将 a,b,c 分别从小到大排序。

结论:最优解存在 i 使得 x\in[a_i,a_{i+1}],y\in[b_i,b_{i+1}],z\in[c_i,c_{i+1}]。

证明:不失一般性地,设 x\in(a_p,a_{p+1}],y\in[a_q,a_{q+1}) 且 p<q。此时一直增大 x,减小 y,代价为 p-(n-p)+(n-q)-q=2(p-q)<0。

那么考虑 x+y+z=0 的限制,可以确定唯一的 i。在 i 的区间内部调整直至 x+y+z=0 即可。

复杂度 \mathcal O(\text{sort}(n))。

Code

#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
#define ppc(x) __builtin_popcount(x)
using namespace std;
namespace Milkcat {
    typedef long long LL;
    typedef pair<LL, LL> pii;
    const int N = 1e6 + 5;
    LL n, x, y, z, t, d, rs, a[N], b[N], c[N];
    int main() {
        cin >> n, rs = 0;
        REP(i, 1, n) cin >> a[i] >> b[i] >> c[i];
        sort(a + 1, a + 1 + n);
        sort(b + 1, b + 1 + n);
        sort(c + 1, c + 1 + n);
        REP(i, 1, n)
            if (a[i] + b[i] + c[i] >= 0) { t = i; break; }
        x = a[t], y = b[t], z = c[t];
        if (t > 1) {
            x -= min(x - a[t - 1], x + y + z);
            y -= min(y - b[t - 1], x + y + z);
            z -= min(z - c[t - 1], x + y + z);
        }
        REP(i, 1, n)
            rs += abs(x - a[i]) + abs(y - b[i]) + abs(z - c[i]);
        cout << rs / 2 << '\n';
        return 0;
    }
}
int main() {
    cin.tie(0)->sync_with_stdio(0);
    int T = 1; cin >> T;
    while (T --) Milkcat::main();
    return 0;
}