luoguP3964 [TJOI2013]松鼠聚会
首先这个距离就叫做切比雪夫距离,即\(qdis(\{x_1,y_1\},\{x_2,y_2\})=\max(|x_1-x_2|,|y_1-y_2|)\)
可以证明\(\max(|x_1-x_2|,|y_1-y_2|)=\frac{|x_1-x_2+y_1-y_2|+|x_1-x_2-y_1+y_2|}2\).
于是我们就将切比雪夫距离转化成了曼哈顿距离.
于是我们可以对于\(x\)坐标与\(y\)坐标分别处理,问题就变成一维的了.
这里详细阐述\(x\)坐标的情况,\(y\)坐标类似.
首先将\(x\)坐标排序.
于是对于点\(i\),所有点到\(i\)的距离可以表示为:
\[\begin{align}
dis_i&=(x_i-x_1)+…+(x_i-x_{i-1})+(x_{i+1}-x_i)+…+(x_n-x_i)\\
&=x_i*(i-1)-\sum_{j=1}^{i-1}x_j+\sum_{j=i+1}^{n}x[j]-x_i*(n-i)\\
&=\sum_{j=1}^{n}x_j-2\sum_{j=1}^{i-1}x_j-x_i*(n-2i)
\end{align}
\]
于是就可以\(\Theta(nlog_2n)\)解决了.
一定记得开\(longlong\)和最后答案除以\(2\)!
#pragma GCC optimize(3)
#include<bits/stdc++.h>
#define il inline
#define rg register
#define gi read<int>
using namespace std;
typedef long long ll;
const int O = 1e5 + 10, M = 6e4;
struct Coord { ll x, y; int id; } a[O];
template<class TT>
il TT read() {
TT o = 0,fl = 1; char ch = getchar();
while (!isdigit(ch) && ch != '-') ch = getchar();
if (ch == '-') fl = -1, ch = getchar();
while (isdigit(ch)) o = o * 10 + ch - '0', ch = getchar();
return fl * o;
}
int n;
ll pre, all, ans[O], res = -1ll << 62;
il bool cmp1(Coord x, Coord y) {return x.x < y.x;}
il bool cmp2(Coord x, Coord y) {return x.y < y.y;}
int main() {
n = gi();
for (int i = 1; i <= n; ++i) {
int X = gi(), Y = gi();
a[i] = (Coord){X + Y, X - Y, i};
all += X;
}
sort(a + 1, a + n + 1, cmp1);
for (int i = 1; i <= n; ++i) {
pre += a[i].x << 1;
ans[a[i].id] = 1ll * a[i].x * (n - i * 2) + pre;
}
sort(a + 1, a + n + 1, cmp2); pre = 0;
for (int i = 1; i <= n; ++i) {
pre += a[i].y << 1;
res = max(res, ans[a[i].id] + pre + 1ll * a[i].y * (n - i * 2));
}
printf("%lld\n", all - (res >> 1));
return 0;
}