V

来源:互联网 发布:java计算时间转换 编辑:程序博客网 时间:2024/03/29 07:20

Description

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

43 62 40 24 7

Sample Output

4




题目分析

给出数轴上的n个区间,每个区间都是连续的int区间。
现在要在数轴上任意取一堆元素,构成一个元素集合V
要求每个区间和元素集合V的交集至少有两个不同的元素
求集合V最小的元素个数。

解题思路

读完题的第一感觉是有些懵

后来想了想可以用贪心

先对所有区间按末端点排序
取第i个区间的最后两个元素a和b
若第i+1个区间包含了这两个元素,则跳到下一个区间所取的元素个数+0
若第i+1个区间只包含了这两个元素中的一个(由于有序,所以必定是包含b),则取第i+1个区间的最后一个元素,所取的元素个数+1。为了方便下一区间的比较,更新a和b的值,使他们为当前V集合中最后的两个元素。
若第i+1个区间没有包含这两个元素,则第i+1个区间的最后两个元素,所取的元素个数+2。为了方便下一区间的比较,更新a和b的值,使他们为当前V集合中最后的两个元素。
a初始化为第一个区间的最后倒数第2个元素
b初始化为第一个区间的最后的元素
所取的元素个数初始化为2(就是a和b)

源代码

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
    int l,r;
} a[10010];
bool cmp(node A,node B)
{
    if(A.r!=B.r)
        return A.r<B.r;
    else return A.l>B.l;
}
int main()
{
    int i,n,t,t1,t2;
    while(~scanf("%d",&n))//这个也是今天做题的时候刚学到的一个东西,~这个,今天上午提交一上午格式输入错误很难受
    {
        memset(a,0,sizeof(a));
        for(i=0; i<n; i++)
            scanf("%d%d",&a[i].l,&a[i].r);
            sort(a,a+n,cmp);
            int s=2,t1=a[0].r,t2=a[0].r-1;
            for(i=1;i<n;i++)
            {
                if(t2>=a[i].l)
                    continue;
                else if(t2<a[i].l&&t1>=a[i].l)
                {
                    t2=a[i].r;
                    s++;
                }
                else if(t2<a[i].l&&t1<a[i].l)
                {
                    t1=a[i].r;
                    t2=a[i].r-1;
                    s+=2;
                }
                if(t1<t2)
                {
                    t=t1;
                    t1=t2;
                    t2=t;
                }
            }
            printf("%d\n",s);
    }
    return 0;
}

0 0
原创粉丝点击