bzoj 1645 [Usaco2007 Open]City Horizon 城市地平线 堆
题面
解法
可以发现,最后每一个位置的值就是经过多次操作后的最大值
那么我们不妨把每一次操作看成两个事件,一个是在\(l\)位置加入一个数,一个是在\(r\)这个位置删除一个数
将这些事件按照时间排序,然后扫一遍即可
只要处理和上一次中间间隔的最大值,用堆来实现
时间复杂度:\(O(n\ log\ n)\)
代码
#include <bits/stdc++.h>
#define int long long
#define N 100010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Node {
int op, x, v;
bool operator < (const Node &a) const {
return x < a.x;
}
} a[N];
main() {
int n, tot = 0; read(n);
for (int i = 1; i <= n; i++) {
int l, r, v;
read(l), read(r), read(v);
a[++tot] = (Node) {1, l, v};
a[++tot] = (Node) {2, r, v};
}
sort(a + 1, a + tot + 1); int ans = 0;
priority_queue <int> ret, del;
for (int i = 1; i <= tot; i++) {
while (!del.empty() && ret.top() == del.top())
ret.pop(), del.pop();
if (!ret.empty()) ans += (a[i].x - a[i - 1].x) * ret.top();
int j = i;
while (a[j].x == a[i].x) {
if (a[j].op == 1) ret.push(a[j].v);
else del.push(a[j].v);
j++;
}
i = j - 1;
}
while (!del.empty() && ret.top() == del.top())
ret.pop(), del.pop();
if (!ret.empty()) ans += ret.top();
cout << ans << "\n";
return 0;
}