https://acm.hdu.edu.cn/contest/problem?cid=1178&pid=1002
Solution
设龙穴在 ,第 条龙在 。将 分别从小到大排序。
结论:最优解存在 使得 ,,。
证明:不失一般性地,设 , 且 。此时一直增大 ,减小 ,代价为 。
那么考虑 的限制,可以确定唯一的 。在 的区间内部调整直至 即可。
复杂度 。
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;
}