题解:洛谷 CF1486B Eastern Exhibition

【题目来源】

洛谷:CF1486B Eastern Exhibition - 洛谷

【题目描述】

二维平面上有 \(n\) 个点,要找一个点,使得所有点到它的曼哈顿距离( \(x\)\(y\) 的坐标差距之和)之和最小。请问有几个满足该要求的点?

【输入】

First line contains a single integer \(t(1 \leq t \leq 1000)\) — the number of test cases.

The first line of each test case contains a single integer \(n(1 \leq n \leq 1000)\) . Next n lines describe the positions of the houses \((x_i, y_i)\) \((0 \leq x_i, y_i \leq 10^9)\).

It's guaranteed that the sum of all n does not exceed \(1000\).

【输出】

For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house.

【输入样例】

6
3
0 0
2 0
1 2
4
1 0
0 2
2 3
3 1
4
0 0
0 1
1 0
1 1
2
0 0
1 1
2
0 0
2 0
2
0 0
0 0

【输出样例】

1
4
4
4
3
1

【算法标签】

《洛谷 CF1486B Eastern Exhibition》 #排序#

【代码详解】

#include <bits/stdc++.h>
using namespace std;

#define int long long  // 使用长整型
const int MAX_N = 1005;  // 定义数组最大长度
int t, n;                // t: 测试用例数, n: 每个用例的点数
int a[MAX_N], b[MAX_N];  // a: 存储x坐标, b: 存储y坐标

signed main()
{
    // 输入测试用例数
    cin >> t;
    
    // 处理每个测试用例
    while (t--)
    {
        // 初始化数组
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        
        // 输入点数
        cin >> n;
        
        // 输入所有点的坐标
        for (int i = 0; i < n; i++)
            cin >> a[i] >> b[i];
        
        // 对x坐标和y坐标分别排序
        sort(a, a + n);
        sort(b, b + n);
        
        // 计算x方向的可行范围
        int x = a[n / 2] - a[(n - 1) / 2] + 1;
        
        // 计算y方向的可行范围
        int y = b[n / 2] - b[(n - 1) / 2] + 1;
        
        // 输出可行解的个数(x范围 × y范围)
        cout << x * y << endl;
    }
    
    return 0;
}

【运行结果】

6
3
0 0
2 0
1 2
1
4
1 0
0 2
2 3
3 1
4
4
0 0
0 1
1 0
1 1
4
2
0 0
1 1
4
2
0 0
2 0
3
2
0 0
0 0
1
posted @ 2026-03-17 15:32  团爸讲算法  阅读(3)  评论(0)    收藏  举报