# 【BZOJ1645】[Usaco2007 Open]City Horizon 城市地平线【线段树】【矩形面积并】

【题目链接】

/* Pigonometry */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 40005, maxm = maxn << 1;

typedef long long LL;

int n, m, pos[maxm], tr[maxm << 2], mxv[maxm << 2];

struct _line {
int l, r, w;
} line[maxn];

int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}

inline int find(int x) {
int l = 1, r = m;
while(l <= r) {
int mid = l + r >> 1;
if(pos[mid] < x) l = mid + 1;
else if(pos[mid] == x) return mid;
else r = mid - 1;
}
}

inline void pushup(int p) {
tr[p] = max(tr[p << 1], tr[p << 1 | 1]);
}

inline void pushdown(int p) {
if(mxv[p]) {
int l = p << 1, r = p << 1 | 1;
mxv[l] = max(mxv[l], mxv[p]);
mxv[r] = max(mxv[r], mxv[p]);
tr[l] = max(tr[l], mxv[p]);
tr[r] = max(tr[r], mxv[p]);
}
}

inline void change(int p, int l, int r, int x, int y, int c) {
if(x <= l && r <= y) {
tr[p] = max(tr[p], c);
mxv[p] = max(mxv[p], c);
return;
}
int mid = l + r >> 1;
pushdown(p);
if(x <= mid) change(p << 1, l, mid, x, y, c);
if(y > mid) change(p << 1 | 1, mid + 1, r, x, y, c);
pushup(p);
}

inline int query(int p, int l, int r, int x) {
if(l == r && r == x) return tr[p];
int mid = l + r >> 1;
pushdown(p);
if(x <= mid) return query(p << 1, l, mid, x);
else return query(p << 1 | 1, mid + 1, r, x);
}

int main() {
n = iread(); m = n << 1;

for(int i = 1; i <= n; i++) {
line[i] = (_line){l, r, w};
pos[(i << 1) - 1] = l; pos[i << 1] = r;
}

sort(pos + 1, pos + 1 + m);
m = unique(pos + 1, pos + 1 + m) - (pos + 1);
for(int i = 1; i <= n; i++) {
line[i].l = find(line[i].l);
line[i].r = find(line[i].r);
change(1, 1, m, line[i].l, line[i].r - 1, line[i].w);
}

LL ans = 0;
for(int i = 1; i < m; i++)
ans += (LL)(pos[i + 1] - pos[i]) * query(1, 1, m, i);

printf("%lld\n", ans);
return 0;
}


05-18 287

02-26 132
01-01 401
08-09 993
03-24 172
10-17 27