• Integer Intervals(贪心)


    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 12123   Accepted: 5129

    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

    4
    3 6
    2 4
    0 2
    4 7
    

    Sample Output

    4

    题意:在数轴上给n个区间,区间上的点均是整数,再在数轴上取x个点构成的点集V使得V与上述每个区间的交集至少包含两个交点,输出满足题意的x的最小值。
    思路:可以贪心,先按每个区间的有端点升序排序,
    初始化:计数器 sum = 2,集合V的前两个元素selem,telem为第一个区间的最后两个整数;(selem和telem在整个循环中作为集合V的最后两个元素,所以必要时更新其值)
    for:
      若第i+1个区间包含selem和telem,不需要做任何改变;
      若第i+1个区间只包含telem,更新selem和telem,sum加1;
      若第i+1个区间不包含selem和telem,更新selem和telem,sum加2;
     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<algorithm>
     4 using namespace std;
     5 
     6 struct node
     7 {
     8     int s,t;
     9 }L[10010];
    10 int cmp(const struct node &a, const struct node &b)
    11 {
    12     return a.t < b.t;
    13 }
    14 
    15 int main()
    16 {
    17     int n;
    18     scanf("%d",&n);
    19     for(int i = 0; i < n; i++)
    20         scanf("%d %d",&L[i].s,&L[i].t);
    21     sort(L,L+n,cmp);
    22     int sum,selem,telem;
    23     sum = 2;
    24     selem = L[0].t-1;
    25     telem = L[0].t;
    26     for(int i = 1; i < n;)
    27     {
    28         if(selem >= L[i].s && selem <= L[i].t && telem >= L[i].s && telem <= L[i].t)
    29             i++;
    30         else if(selem < L[i].s && telem >= L[i].s && telem <= L[i].t)
    31         {
    32             selem = telem;
    33             telem = L[i].t;
    34             sum++;
    35             i++;
    36         }
    37         else if(selem < L[i].s && telem < L[i].s)
    38         {
    39             selem = L[i].t-1;
    40             telem = L[i].t;
    41             sum += 2;
    42             i++;
    43         }
    44     }
    45     printf("%d
    ",sum);
    46     return 0;
    47 }
    View Code
    
    
    
    
  • 相关阅读:
    Bootstrap_让Bootstrap轮播插件carousel支持左右滑动手势的三种方法
    JAVA_用Java来获取访问者真实的IP地址
    Html5_移动前端不得不了解的html5 head 头标签
    ThinkPad_T430重装系统
    JavaScript_JS判断客户端是否是iOS或者Android
    Html5_禁止Html5在手机上屏幕页面缩放
    HttpClient_httpclient 4.3.1 post get的工具类
    HttpClient_使用httpclient必须知道的参数设置及代码写法、存在的风险
    LATEX数学公式基本语法
    为WLW开发Latex公式插件
  • 原文地址:https://www.cnblogs.com/LK1994/p/3411239.html
Copyright © 2020-2023  润新知