P3138 [USACO16FEB] Load Balancing S 题解

· · 题解

Solve

题目中的 N 最多不大于 1000,直接枚举竖直方向和水平方向的栏杆的位置显然不会超时,而我们要做的,就是枚举时 \mathcal{O}(1) 计算四个区域的奶牛数量。不难想到使用二维前缀和即可实现 \mathcal{O}(1) 计算。

// 前缀和
void init() {   // 初始化
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j];
{
int calc(int x1, int y1, int x2, int y2) {   // 左上角 (x1, y1),右下角 (x2, y2) 的矩形 
    return s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]; 
}

仔细观察题目,发现 x,y\le 10^6,直接开一个这么大的二维前缀和数组空间会飞起,而 N 很小,于是考虑离散化。

如何将一些类似 (x_i,y_i) 的坐标离散化呢?

只需要将 x 坐标和 y 坐标分别离散化即可,发现这样可以在不改变每个元素的位置,也不改变 x 坐标和 y 坐标的相对大小的情况下尽可能地压缩 x 和 y 坐标。

例如,将坐标 \{(4,19),(114514,520),(520,1919810)\} 对 x 坐标和 y 坐标分别离散化后得到 \{(1,1),(3,2),(2,3)\}。

for (int i = 1; i <= n; i++) 
    nx[i].idx = ny[i].idx = i;
sort(nx + 1, nx + n + 1, cmp);
sort(ny + 1, ny + n + 1, cmp);
// 离散化
for (int i = 1; i <= n; i++) 
    x[nx[i].idx] = y[ny[i].idx] = i;

Code

#include <iostream>
#include <algorithm>
using namespace std;
int n, x[1010], y[1010], s[1010][1010];
struct node {
    int x, idx;
} nx[1010], ny[1010];
bool cmp(node a, node b) {
    return a.x < b.x;
}
int calc(int x1, int y1, int x2, int y2) {
    return s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]; 
}
int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        nx[i].idx = ny[i].idx = i;
        cin >> nx[i].x >> ny[i].x;
    }
    sort(nx + 1, nx + n + 1, cmp);
    sort(ny + 1, ny + n + 1, cmp);
    for (int i = 1; i <= n; i++) 
        x[nx[i].idx] = y[ny[i].idx] = i;
    for (int i = 1; i <= n; i++)
        s[x[i]][y[i]]++;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            s[i][j] += s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1];
    int ans = 1e9;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) {
            int now = max(max(max(calc(1, 1, i, j), calc(1, j + 1, i, n)), calc(i + 1, 1, n, j)), calc(i + 1, j + 1, n, n));
            ans = min(ans, now);
        }
    cout << ans << endl;
    return 0; 
}