#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
/*代码来自大佬*/
typedef long long ll;
const int kMax = 50000 + 10;
struct P {
int x, p, v;
P(int _x = 0, int _p = 0, int _v = 0) : x(_x), p(_p), v(_v) {}
bool operator < (const P& t) const {
return x < t.x;
}
} pos[kMax << 1];
struct node {
int l, r, times, add;
ll sum;
} tree[kMax << 3];
int n;
int num[kMax][4], old[kMax << 1];
map<int, int> table;
void pushup(int p) {
tree[p].times = min(tree[p << 1].times, tree[p << 1 | 1].times);
}
void pushdown(int p) {
if(tree[p].add) {
tree[p << 1].times += tree[p].add;
tree[p << 1 | 1].times += tree[p].add;
tree[p << 1].add += tree[p].add;
tree[p << 1 | 1].add += tree[p].add;
tree[p].add = 0;
}
}
void build(int p, int l, int r) {
tree[p].l = l;
tree[p].r = r;
tree[p].add = 0;
tree[p].times = 0;
tree[p].sum = old[r] - old[l - 1];//一个点代表横坐标其中一段,r=1代表0-1
if(l == r) return;
int m = (l + r) >> 1;
build(p << 1, l, m);
build(p << 1 | 1, m + 1, r);
}
void update(int p, int l, int r, int v) {
if(l <= tree[p].l && r >= tree[p].r) {
tree[p].times += v;
tree[p].add += v;
return;
}
pushdown(p);
int m = (tree[p].l + tree[p].r) >> 1;
if(l <= m) update(p << 1, l, r, v);
if(r > m) update(p << 1 | 1, l, r, v);
pushup(p);
}
ll query(int p) {
if(tree[p].times) return tree[p].sum;
if(tree[p].l == tree[p].r) return 0;
pushdown(p);
return query(p << 1) + query(p << 1 | 1);
}
int main() {
scanf("%d", &n);//n个矩形
for(int i = 0;i < n;++ i) {
for(int j = 0;j < 4;++ j) {
scanf("%d", &num[i][j]);
pos[i] = {num[i][1], i, 1};//y1
pos[n + i] = {num[i][3], i, -1};//y2
old[i] = num[i][0];//x1
old[n + i] = num[i][2];//x2
}
}
sort(pos, pos + n * 2);//排序,自下向上扫描
sort(old, old + n * 2);//排序。方便去重
int len = unique(old, old + n * 2) - old;//去重
for(int i = 0;i < len;++ i) {//数据离散化
table[old[i]] = i + 1;
}
build(1, 1, len);//构造线段树
ll cur = 0, res = 0;
for(int i = 0;i < n * 2;++ i) {//更新x1至x2,因为table[old[i]] = i + 1,所以r需要-1.比如表示0-10,实际下标是1到10,离散化成1-11了,所以l不变,r-1。篇幅限制没有讲清楚,辅助个人理解而已。
update(1, table[num[pos[i].p][0]], table[num[pos[i].p][2]] - 1, pos[i].v);
if(i) res += (pos[i].x - pos[i - 1].x) * cur;//y2-y1乘以上次的长度
cur = query(1);
}
printf("%lld\n", res);//当前长度
return 0;
}
线扫描之面积并
最新推荐文章于 2020-02-01 13:23:31 发布