题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1264
题目解析:
给出矩形对角线两个坐标,可以推出矩形左下角和右上角坐标;
用hash二维数组存储每个正方形是否被覆盖到,覆盖到标记为1,用于去重;
从左下角开始遍历每行的正方形到右上角为止,对于覆盖到的正方形,假设正方形左下角坐标 ( i, j ),则将 hash[i][j] 设置为 1;
最后遍历二维数组hash,看有多少个1;
/*题意:每行给出4个数字,分别为两个坐标值,这两个坐标为一个矩形的对角坐标,
也就是说,这4个数字代表两个坐标从而确定了一个矩形。。当4个数字都为-1时,表示一组数据结束;
当4个数字都为-2时,表示程序结束。求的是一组数据的各个矩形并下来覆盖的面积。
*/
#include <stdio.h> //简单hash
#include <algorithm>
int hash[101][101];
void swap(int& x, int& y) {
int temp;
temp = x;
x = y;
y = temp;
}
int main() {
int x1, y1, x2, y2;
while (scanf("%d %d %d %d", &x1, &y1, &x2, &y2) != EOF) {
if (x1 == x2 && x2 == y1 && y1 == y2 && y2 == -2) {
break;
}
memset(hash, 0, sizeof(hash));
while (1) {
if (x1 == x2 && x2 == y1 && y1 == y2 && y2 == -1) {
break;
}
if (x1 == x2 && x2 == y1 && y1 == y2 && y2 == -2) {
break;
}
if (x1 > x2) {
swap(x1, x2);
}
if (y1 > y2) {
swap(y1, y2);
}
for (int i = x2; i > x1; i--) {
for (int j = y2; j > y1; j--) {
hash[i][j] = 1;
}
}
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
}
int count = 0;
for (int i = 100; i > 0; i--) {
for (int j = 100; j > 0; j--) {
if (hash[i][j]) {
count++;
}
}
}
printf("%d\n", count);
}
return 0;
}