Chiaki has n intervals and the i-th of them is [li,ri] . She wants to delete some intervals so that there does not exist three intervals a, b and c such that a intersects with b, b intersects with c and c intersects with a.
Chiaki is interested in the minimum number of intervals which need to be deleted.
Note that interval a intersects with interval b if there exists a real number x such that la≤x≤ra and lb≤x≤rb .
解题思路
贪心策略,对于 [lx,rx], [ly,ry], [lz,rz] ,若三个区间存在交集,考虑如何删除一个区间使得剩余所有区间重合尽可能小,对于区间左值从小到大进行遍历的策略,则应将 max(rx,ry,rz) 删除,可最大限度的避免后续遍历中的区间交集问题。
代码
#include<bits/stdc++.h>
using namespace std;
struct Inv {
int l, r, idx;
} p[50010], s[3];
bool cmp_l(Inv a, Inv b){ return a.l < b.l; }
bool cmp_gt_r(Inv a, Inv b){ return a.r > b.r; }
bool cmp_lt_r(Inv a, Inv b){ return a.r < b.r; }
int id[100010];
int main()
{
int T, n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
int cnt = 0;
for(int i=1;i<=n;i++)
scanf("%d %d",&p[i].l, &p[i].r), p[i].idx = i;
sort(p+1, p+n+1, cmp_l);
vector<int> ans; ans.clear();
for(int i=1, num = 0;i<=n;i++)
{
sort(s, s+num, cmp_gt_r);
if(num && s[num-1].r < p[i].l) num--;
s[num++] = p[i];
if(num == 3)
{
sort(s, s+num, cmp_lt_r);
ans.push_back(s[2].idx);
num--;
}
}
printf("%d\n", ans.size());
sort(ans.begin(), ans.end());
for(int i=0;i<ans.size();i++)
printf("%d%c", ans[i], (i==ans.size()-1?'\n':' '));
}
}