二分贪心练习题-V22


  
  
An integer interval [a,b], a < b, is a set of all consecutive integers beginning with a and ending with b.  Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval.

Input

The first line of the input contains the number of intervals n, 1 <= n <= 10000. Each of the following n lines contains two integers a, b separated by a single space, 0 <= a < b <= 10000. They are the beginning and the end of an interval.

Output

Output the minimal number of elements in a set containing at least two different integers from each interval.

Sample Input

4
3 6
2 4
0 2
4 7

Sample Output

4
题意:
    给出一组区间,找出一组数,使每个区间中至少有两个数在这组数中。
思路:
    这和课上讲的差不多都是贪心做,先将该区间按区间[a,b]中b作为排序,用一个数组标记该组数是否有此数,然后对每一个区间遍历,看此区间中有几个数,1,没有就选取区间最后两个数,2,有一个数,选取区间最后一个数。3,有两个数则不用管。累加统计被标记数。
#include <iostream>
#include <algorithm>
#include<stdio.h>
#include<vector>
#include<string.h>
#include<string>
using namespace std;
struct code
{
    int x,y;
}a[10001];
bool cmp(code j,code k)
{
    if(j.y!=k.y)return (j.y<k.y);
    else return (j.x<k.x);
}
int main()
{
    int b[10001],cnt=0,sum=0,n;
    memset(b,0,sizeof(b));
    cin>>n;
    for(int i=0;i<n;i++)
    {cin>>a[i].x>>a[i].y;}
    sort(a,a+n,cmp);
    b[a[0].y]=1;
    b[a[0].y-1]=1;
    cnt=2;
    for(int i=1;i<n;i++)
    {
        sum=0;
        for(int j=a[i].x;j<=a[i].y;j++)
        {
            if(b[j])sum++;
            if(sum==2)break;
        }
        if(sum==1)
        {
            b[a[i].y]=1;
            cnt++;
        }
        if(sum==0)
        {
            b[a[i].y]=1;
            b[a[i].y-1]=1;
            cnt=cnt+2;
        }
    }
    cout<<cnt;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值