这是我的第一道离散化题,虽然只是一道普及-的题,但我理解起来还是有点吃力,看完视频后我我觉的离散化,就是将一堆数据用他们的相对大小表示 例如 1,99,100,1000,可以表示为1,2,3,4.
55 100 300 1,可以表示为 2 3 4 1;这道题目就是先把各个区间的两个端点存储到c数组,对c进行排序后中然后用二分查找各个数据在c中的相对位置
这里要注意,标记f数组时应该<b[i],应为我们是用后一个数减前一个数,如果不这样的话,例如,1 5,8 10,两个区间,答案就会加上8-5这是不正确的
#include<iostream>
#include<set>
#include<map>
#include<algorithm>
#include<vector>
#include<cmath>
#include<climits>
#include<cstring>
#define int long long
const int N = 1e6+5;
using namespace std;
char* p1, * p2, buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int read()
{int x = 0, f = 1;char ch = nc();while (ch < 48 || ch>57){if (ch == '-')f = -1;ch = nc();}while (ch >= 48 && ch <= 57)x = x * 10 + ch - 48, ch = nc();return x * f;
}
int a[N], b[N], c[N],f[N];
signed main() {ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);int n;cin >> n;vector<int>v;int k = 0;for (int i = 1; i <= n; i++) {cin >> a[i] >> b[i];c[++k] = a[i];c[++k] = b[i];}sort(c + 1, c + 1 + 2 * n);for (int i = 1; i <= n; i++) {a[i] = lower_bound(c + 1, c + 1 + 2 * n, a[i])-c;b[i] = lower_bound(c + 1, c + 1 + 2 * n, b[i]) - c;for (int j = a[i]; j < b[i]; j++)f[j] = 1;}int cnt = 0;for (int i = 1; i < 2 * n; i++) {if (f[i] == 1)cnt += c[i+1] - c[i];}cout << cnt;return 0;
}