跳到正文

题解

HDU25.8.8 1002 龙族栖息地 题解

喵仔牛奶约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月23日
篇幅
约 3 分钟

版本

  1. v1当前

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

Solution

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

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

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

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

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

Code

C++
#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;
}
原文