跳到正文

题解

P3138 [USACO16FEB] Load Balancing S 题解

guitarhero_0221约 4 分钟
原文
文章信息与版本

文章信息

发布
2022年8月7日
收录
2026年9月29日
更新
2026年11月9日
篇幅
约 4 分钟
获赞
1
题目
P3138

版本

  1. v1当前

Solve

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

C++
// 前缀和
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≤106x,y\le 10^6,直接开一个这么大的二维前缀和数组空间会飞起,而 NN 很小,于是考虑离散化。

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

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

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

C++
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

C++
#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; 
}