题意
传送门 POJ 1177 Picture
题解
求矩形面积并的周长。扫描线法求解,将矩形用 ( x 1 , y 1 , y 2 , 1 ) , ( x 2 , y 1 , y 2 , − 1 ) (x_1,y_1,y_2,1),(x_2,y_1,y_2,-1) (x1,y1,y2,1),(x2,y1,y2,−1) 表示,顺序扫描 x x x 轴,同时维护离散化的 y y y 轴各区域被覆盖的矩形面积数。周长中平行于 x x x 轴的部分,为各扫描线间距离乘以 x x x 方向矩形与未覆盖区域的边界数之和;平行于 y y y 轴的部分,为各扫描线间 y y y 方向矩形与未覆盖区域交界的长度之和。为了方便处理边界, x , y x,y x,y 轴部分加入极大、极小值。上述扫描线间的统计可以 O ( N ) O(N) O(N) 朴素地求解,总时间复杂度 O ( N 2 ) O(N^2) O(N2)。
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 5005, maxx = 10005;
struct node
{
int x, y1, y2, d;
bool operator<(const node &b) const { return x < b.x; }
} A[maxn << 1];
int N, res, L[maxn << 1], tmp[maxn << 1], ny, sy[maxn << 1];
inline int cp(int y) { return lower_bound(sy, sy + ny, y) - sy; }
inline void add1(int x)
{
int d = 0;
for (int i = 1; i < ny; ++i)
d += (bool)L[i] != (bool)L[i - 1];
res += x * d;
}
inline void add2()
{
for (int i = 0; i + 1 < ny; ++i)
res += (bool)L[i] != (bool)tmp[i] ? sy[i + 1] - sy[i] : 0;
}
int main()
{
scanf("%d", &N);
for (int i = 0, j = 0, x1, y1, x2, y2; i < N; ++i)
{
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
A[i] = node{x1, y1, y2, 1}, A[N + i] = node{x2, y1, y2, -1};
sy[j++] = y1, sy[j++] = y2;
}
ny = (N <<= 1);
A[N++] = node{-maxx, 0, 0, 0}, A[N++] = node{maxx, 0, 0, 0};
sort(A, A + N);
sy[ny++] = -maxx, sy[ny++] = maxx;
sort(sy, sy + ny);
ny = unique(sy, sy + ny) - sy;
for (int i = 0, l, r; i + 1 < N; ++i)
{
l = cp(A[i].y1), r = cp(A[i].y2);
for (int j = l; j < r; ++j)
L[j] += A[i].d;
if (A[i].x != A[i + 1].x)
{
add1(A[i + 1].x - A[i].x), add2();
memcpy(tmp, L, sizeof(int) * ny);
}
}
printf("%d\n", res);
return 0;
}