算是最基础的线段树扫描线了把。
注意横坐标区间如果是[1, 3]实际长度是2,维护是两个点而不是3个。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<list>
using namespace std;
typedef pair<int,int> PII;
typedef long long LL;
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
const int INF = 0x3f3f3f3f;
const int Maxn = 33333 + 10;
int x[Maxn<<1], n, sum[Maxn<<3], cnt[Maxn<<3], x_num, line_num;
LL ans;
struct Line{
int l, r, h, s;
Line(){}
Line(int ll, int rr, int hh ,int ss):l(ll), r(rr), h(hh), s(ss){}
bool operator < (const Line &l) const{
return h < l.h;
}
}L[Maxn<<1];
void build(){
memset(sum, 0, sizeof(sum));
memset(cnt, 0, sizeof(cnt));
x_num = line_num = 0;
ans = 0;
}
void pushUp(int rt, int l, int r){
if(cnt[rt]) sum[rt] = x[r+1] - x[l];
else if(l == r) sum[rt] = 0;
else sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void update(int L, int R, int s, int l, int r, int rt){
if(L <= l && R >= r){
cnt[rt] += s;
pushUp(rt, l, r);
return;
}
int m = (l+r) >> 1;
if(m >= R) update(L, R, s, lson);
else if(m < L) update(L, R, s, rson);
else{
update(L, m, s, lson);
update(m+1, R, s, rson);
}
pushUp(rt, l, r);
}
int search(int k){
int l = 1, r = x_num, m;
while(l<=r){
m = (l + r) >> 1;
if(x[m] == k) return m;
else if(k < x[m]) r = m - 1;
else l = m + 1;
}
return -1;
}
int main()
{
int T, cas=1;
scanf("%d", &T);
while(T--){
scanf("%d", &n);
build();
for(int i=0;i<n;i++){
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
x[++x_num] = a;
x[++x_num] = c;
L[line_num++] = Line(a, c, b, 1);
L[line_num++] = Line(a, c, d, -1);
}
sort(x+1, x+x_num+1);
sort(L, L+line_num);
int temp = 1;
for(int i=2;i<=x_num;i++){
if(x[i] != x[i-1]) x[++temp] = x[i];
}
ans = 0;
x_num = temp;
for(int i=0;i<line_num;i++){
int l = search(L[i].l);
int r = search(L[i].r)-1;
if(!i) update(l, r, L[i].s, 1, x_num, 1);
else{
ans += (LL)sum[1]*(L[i].h - L[i-1].h);
update(l, r, L[i].s, 1, x_num, 1);
}
}
printf("Case %d: %lld\n", cas++, ans);
}
return 0;
}