# P5490 【模板】扫描线 & 矩形面积并
题目描述
求 个四边平行于坐标轴的矩形的面积并。
输入格式
第一行一个正整数 。
接下来 行每行四个非负整数 ,表示一个矩形的四个端点坐标为 。
输出格式
一行一个正整数,表示 个矩形的并集覆盖的总面积。
输入输出样例 #1
输入 #1
2
100 100 200 200
150 150 250 255
输出 #1
18000
说明/提示
对于 的数据,。
对于 的数据,,,。
Updated on 4.10 by Dengduck(口胡) & yummy(实现):增加了一组数据。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int>PII;
const int N=1e6+10;
const int mod=998244353;
const int INF = 0x3f3f3f3f;
const ll INFll = 0x3f3f3f3f3f3f3f3f;
#define endl "\n"
#define x first
#define y second
//vector<vector<int>>adj(N);
vector<int> lsh;
int get(int x) {
return lower_bound(lsh.begin(), lsh.end(), x) - lsh.begin();
}
ll perim = 0, area = 0;
struct Node{
int l, r;
ll len, len2, cnt;
} tr[N];
void pushup(int u) {
if(tr[u].cnt) tr[u].len2 = tr[u].len;
else tr[u].len2 = tr[u << 1].len2 + tr[u << 1 | 1].len2;
}
void build(int u, int l, int r) {
tr[u].l = l, tr[u].r = r;
tr[u].len = lsh[r + 1] - lsh[l];
tr[u].len2 = tr[u].cnt = 0;
if(l == r) {
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
void modify(int u, int l, int r, int d) {
if(l <= tr[u].l && tr[u].r <= r) {
tr[u].cnt += d;
if(tr[u].cnt) {
tr[u].len2 = tr[u].len;
} else {
if(tr[u].l == tr[u].r) tr[u].len2 = 0;
else tr[u].len2 = tr[u << 1].len2 + tr[u << 1 | 1].len2;
}
return;
}
int mid = tr[u].l + tr[u].r >> 1;
if(l <= mid) modify(u << 1, l, r, d);
if(r > mid) modify(u << 1 | 1, l, r, d);
pushup(u);
}
struct line {
int x, l, r, d;
}L[N];
int n;
int m = 0;
struct JX {
int x1, y1, x2, y2;
}jx[N];
void solve1() {
for(int i = 1; i <= n; i ++) {
auto [x1, y1, x2, y2] = jx[i];
L[++ m] = {x1, y1, y2, 1};
L[++ m] = {x2, y1, y2, -1};
lsh.push_back(y1);
lsh.push_back(y2);
}
lsh.push_back(-INF);
sort(lsh.begin(), lsh.end());
lsh.erase(unique(lsh.begin(), lsh.end()), lsh.end());
build(1, 1, lsh.size() - 2);
sort(L + 1, L + m + 1, [&](line a, line b){
if(a.x != b.x) return a.x < b.x;
return a.d > b.d;
});
for(int i = 1; i <= m; i ++) {
if(i) area += tr[1].len2 * (L[i].x - L[i - 1].x);
auto [x, l, r, d] = L[i];
l = get(l);
r = get(r) - 1;
ll res = tr[1].len2;
modify(1, l, r, d);
res = abs(res - tr[1].len2);
perim += res;
}
m = 0;
lsh.clear();
memset(tr, 0, sizeof tr);
}
void solve()
{
cin >> n;
for(int i = 1; i <= n; i ++) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
jx[i] = {x1, y1, x2, y2};
}
solve1();
for(int i = 1; i <= n; i ++) {
swap(jx[i].x1, jx[i].y1);
swap(jx[i].x2, jx[i].y2);
}
solve1();
cout << perim << " " << area / 2 << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cout << setprecision(11) << fixed;
int t;t=1;
//cin>>t;
for(int i=1;i<=t;i++){
//printf("Case %d: ",i);
solve();
}
return 0;
}