题面
题意
二维平面上有 n个点,要找一个点,使得所有点到它的曼哈顿距离( x 和 y 的坐标差距之和)之和最小。请问有几个满足该要求的点?
题解
- 经典贪心仓库选址问题,不懂点这里,仓库的最优位置就是数组的中位数
- 此题是要在二维的坐标轴上选择最优位置,问最优位置的个数
3.首先,对于二维哈曼顿距离,横纵仓库的最优选择是独立的,那么我们就可以转换成一维的最优解法,然后cntx * cnty 就是仓库的总数 (横纵坐标的个数相乘)
- 那么对于一维的,如果n是奇数,那么最优仓库横纵方向都只有1个,总的仓库也是一个,对于n是偶数,一维仓库的个数就是a[n / 2] - a[n / 2 - 1] + 1(横向),b[n / 2] - b[n / 2 - 1] + 1(纵向),
代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int t, n;
int a[N], b[N];
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
cin >> t;
while (t--) {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i] >> b[i];
}
if (n & 1) {
cout << 1 << endl;
continue;
}
sort(a, a + n), sort(b, b + n);
ll cntx = a[n / 2] - a[n / 2 - 1] + 1;
ll cnty = b[n / 2] - b[n / 2 - 1] + 1;
cout << cntx * cnty << endl;
}
return 0;
}