P5542 [USACO19FEB]Painting The Barn S(二维差分)(前缀和)
程序员文章站
2022-03-21 17:41:20
...
#include <cstdio>
#include <iostream>
using namespace std;
const int maxn = 1005;
int n, k, ans;
int fx, tx, fy, ty;
int a[maxn][maxn], sum[maxn][maxn];
inline int read(void) { //快读
int s = 0, w = 1;
char ch = getchar();
for (; ch < '0' || ch > '9'; ch = getchar())
if (ch == '-')
w = -1;
for (; ch <= '9' && ch >= '0'; ch = getchar())
s = s * 10 + ch - '0';
return s * w;
}
int main() {
n = read();
k = read();
for (int i = 0; i < n;++i){
fx = read() + 1, fy = read() + 1;
tx = read(), ty = read();
a[fx][fy]++;
a[tx+1][ty+1]++;
a[fx][ty + 1]--;
a[tx + 1][fy]--;
}
for (int i = 1; i <= 1000;++i){
for (int j = 1; j <= 1000;++j){
sum[i][j] = sum[i - 1][j] +sum[i][j - 1] - sum[i - 1][j - 1] + a[i][j];
if(sum[i][j]==k)
ans++;
}
}
cout << ans << endl;
return 0;
}
原理:因为题目所给出的坐标点是坐标线上的点,不利于我们用二维数组直接表示矩形,如下图未经坐标处理前的(1,1)到(5,5)的4*4矩形
下图是经过处理坐标后的(2,2)到(5,5)的4*4矩形
处理之后就可以直观地用二维数组记录每个小矩形的涂色情况
处理完坐标就是对数组进行二维差分和前缀和了,这里可以参考
二维差分:https://blog.csdn.net/justidle/article/details/104506724、
二维前缀和:https://blog.csdn.net/k_r_forever/article/details/81775899
侵删