ZOJ 3953 Intervals (贪心)

7 篇文章 0 订阅

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 laxra and lbxrb .

解题思路

贪心策略,对于 [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':' '));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值