P1496. 火烧赤壁

考点

  • 离散化
  • 差分

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e4 + 50;
int n, btop, b[2 * maxn], ctop, c[2 * maxn], vis[2 * maxn];
unordered_map<int, int> mp;

struct node {
int l_, r_;
} a[maxn];

int main() {
// 离散化处理
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i].l_ >> a[i].r_;
b[++btop] = a[i].l_, b[++btop] = a[i].r_;
}
sort(b + 1, b + 1 + btop);
for (int i = 1; i <= btop; ++i) {
if (i == 1 || b[i] != b[i - 1]) {
c[++ctop] = b[i];
mp[b[i]] = ctop;
}
}
// 差分修改区间
for (int i = 1; i <= n; ++i) {
int l = mp[a[i].l_], r = mp[a[i].r_];
++vis[l], --vis[r];
}
int ans = 0;
for (int i = 1; i <= btop; ++i) {
vis[i] += vis[i - 1];
if (vis[i]) ans += c[i + 1] - c[i];
}
cout << ans;
return 0;
}

思路

离散化的模板题,上《深进》截图。