P3964 [TJOI2013]松鼠聚会
题意:给出 个点 ,找到某个点,使得所有点到该点的切比雪夫距离和最小。
- 一、
三种距离:
①欧几里得距离:
②曼哈顿距离:
③切比雪夫距离: - 二、
相同距离
曼哈顿距离 转化为切比雪夫距离:
切比雪夫距离 转化为曼哈顿距离: - 三、
对于曼哈顿距离:
当前枚举到点 ,那么所有点到该点的距离:
- 如果我们将所有横坐标按照升序排序
- 同理,如果我们将所有纵坐标按照升序排序
发现了啥?这不是前缀和吗?
由此可得AC代码~
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
ll read()
{
ll x = 0, f = 1; char c = getchar();
while(c < '0' || c > '9') { if(c == '-') f = -f; c = getchar(); }
while(c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
return x * f;
}
const int maxN = 100005;
struct node{
ll x, y;
int id;
node() {}
node(ll a, ll b, int c) : x(a), y(b), id(c) {}
}mp[maxN];
bool cmp_x(node n1, node n2) { return n1.x < n2.x; }
bool cmp_y(node n1, node n2) { return n1.y < n2.y; }
ll n;
ll ans[maxN];
ll sum[maxN];
int main()
{
n = read();
for(int i = 1; i <= n; ++ i )
{
mp[i].x = read(); mp[i].y = read();
ll xx = mp[i].x + mp[i].y, yy = mp[i].x - mp[i].y;
mp[i] = node(xx, yy, i);
}
sort(mp + 1, mp + n + 1, cmp_x);
for(int i = 1; i <= n; ++ i )
sum[i] = sum[i - 1] + mp[i].x;
for(int i = 1; i <= n; ++ i )
ans[mp[i].id] = (i * mp[i].x - sum[i] + sum[n] - sum[i] - (n - i) * mp[i].x);
sort(mp + 1, mp + n + 1, cmp_y);
for(int i = 1; i <= n; ++ i )
sum[i] = sum[i - 1] + mp[i].y;
for(int i = 1; i <= n; ++ i )
ans[mp[i].id] += (i * mp[i].y - sum[i] + sum[n] - sum[i] - (n - i) * mp[i].y);
ll res = ans[1];
for(int i = 2; i <= n; ++ i )
res = min(res, ans[i]);
cout << (res >> 1) << endl;
return 0;
}