由于数据量很小,直接将每个矩形离散化,即拆分成小正方形,并记录每个小正方形的颜色,最后扫描一遍全图即可。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 105;
int X[MAXN * 2]; //所有左上角和右下角的X坐标
int Y[MAXN * 2]; //所有左上角和右下角的Y坐标
int color[MAXN * 2][MAXN * 2]; //每个小格子的颜色
int area[MAXN]; //每种颜色的面积
struct Rectangle //矩形
{
int x1, y1, x2, y2; //左上角坐标,右下角坐标
int c; //颜色
}r[MAXN];
int main()
{
int Case = 1;
int H, W;
while (cin >> H >> W)
{
if (H == 0 && W == 0)
break;
int N;
cin >> N;
int total = 0;
for (int i = 0; i < N; i++) //输入
{
cin >> r[i].x1 >> r[i].y1 >> r[i].x2 >> r[i].y2 >> r[i].c;
X[total] = r[i].x1;
X[total + 1] = r[i].x2;
Y[total] = r[i].y1;
Y[total + 1] = r[i].y2;
total += 2;
}
sort(X, X + total);
sort(Y, Y + total);
int lenX = unique(X, X + total) - X; //去重后X数组的长度
int lenY = unique(Y, Y + total) - Y; //去重后Y数组的长度
memset(color, 0, sizeof(color));
memset(area, 0, sizeof(area));
for (int i = 0; i < N; i++) //涂色
{
int stX = lower_bound(X, X + lenX, r[i].x1) - X;
int endX = lower_bound(X, X + lenX, r[i].x2) - X;
int stY = lower_bound(Y, Y + lenY, r[i].y1) - Y;
int endY = lower_bound(Y, Y + lenY, r[i].y2) - Y;
for (int j = stX; j < endX; j++)
{
for (int k = stY; k < endY; k++)
color[j][k] = r[i].c;
}
}
for (int i = 0; i < lenX - 1; i++) //扫描全图
{
for (int j = 0; j < lenY - 1; j++)
{
if (color[i][j])
area[color[i][j]] += ((X[i + 1] - X[i]) * (Y[j + 1] - Y[j]));
}
}
if (Case > 1)
cout << endl;
cout << "Case " << Case++ << ":" << endl;
int num = 0;
for (int i = 1; i < MAXN; i++)
{
if (area[i] != 0)
{
cout << i << " " << area[i] << endl;
++num;
}
}
if (num == 1)
cout << "There is " << num << " color left on the wall." << endl;
else
cout << "There are " << num << " colors left on the wall." << endl;
}
return 0;
}
继续加油。