线段树 + 离散化,
为什么要在相邻数字只差大于1之间插入一个大于前小于后的数?
大概就是就是找一个数代替alls相邻数字之间所缺的一段区间,这样只有将相邻数字区间覆盖才能覆盖掉新插入的点。
离散化后就是染色问题了,w代表此时该点最上面的画,也可以理解为一种颜色,w为0无颜色,-1有多种颜色,大于 0有颜色
代码:
#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <climits>
#include <iomanip>
#include <queue>
#include <vector>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl
#define lson idx << 1
#define rson idx << 1 | 1
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;
int n, m;
struct node
{
int l, r;
ll w; //w为0无颜色,-1多种颜色,大于 0 有颜色
} tree[N << 2];
int lazy[N << 2];
int li[N], ri[N];
vector<int> alls;
int res[N] = {0};
inline void PushUp(int idx)
{
if (tree[lson].w == tree[rson].w)
tree[idx].w = tree[lson].w;
else
tree[idx].w = -1;
}
inline void PushDown(int idx)
{
if (lazy[idx] != 0)
{
lazy[lson] = lazy[idx];
lazy[rson] = lazy[idx];
tree[lson].w = lazy[idx];
tree[rson].w = lazy[idx];
lazy[idx] = 0;
}
}
void Build(int idx, int l, int r)
{
lazy[idx] = 0;
tree[idx].l = l;
tree[idx].r = r;
if (l == r)
{
tree[idx].w = 0;
return;
}
int mid = l + r >> 1;
Build(lson, l, mid);
Build(rson, mid + 1, r);
PushUp(idx);
}
inline void Update(int idx, int l, int r, int k)
{
if (tree[idx].l >= l && tree[idx].r <= r)
{
tree[idx].w = k;
lazy[idx] = k;
return;
}
PushDown(idx);
if (tree[lson].r >= l)
Update(lson, l, r, k);
if (tree[rson].l <= r)
Update(rson, l, r, k);
PushUp(idx);
}
inline void Query(int idx, int l, int r)
{
if (tree[idx].l >= l && tree[idx].r <= r && tree[idx].w != -1)
{
res[tree[idx].w]++;
return;
}
PushDown(idx);
if (tree[lson].r >= l)
Query(lson, l, r);
if (tree[rson].l <= r)
Query(rson, l, r);
}
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> n;
for (int i = 1; i <= n; i++)
{
scanf("%d%d", &li[i], &ri[i]);
alls.push_back(li[i]), alls.push_back(ri[i]);
}
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
//插点
int sz = alls.size();
for (int i = 0; i < sz - 1; i++)
{
if (alls[i + 1] - alls[i] > 1)
alls.push_back(alls[i + 1] - 1);
}
sort(alls.begin(), alls.end());
Build(1, 1, alls.size());
for (int i = 1; i <= n; i++)
{
int l = lower_bound(alls.begin(), alls.end(), li[i]) - alls.begin() + 1; //因为我是从1开始建树的所以,而这里的索引值从0开始所以要加1
int r = lower_bound(alls.begin(), alls.end(), ri[i]) - alls.begin() + 1;
Update(1, l, r, i);
}
Query(1, 1, alls.size());
int ans = 0;
for (int i = 1; i <= n; i++)
if (res[i])
ans++;
printf("%d\n", ans);
alls.clear();
memset(res, 0, sizeof res);
}
return 0;
}
思路来源:https://www.cnblogs.com/ctyakwf/p/12303151.html,离散化里面解释的更清楚。