zoukankan      html  css  js  c++  java
  • 整数区间

    整数区间
    请编程完成以下任务:   
    1.从文件中读取闭区间的个数及它们的描述;   
    2.找到一个含元素个数最少的集合,使得对于每一个区间,都至少有一个整数属于该集合,输出该集合的元素个数。
    【输入】
    首行包括区间的数目n,1<=n<=10000,接下来的n行,每行包括两个整数a,b,被一空格隔开,0<=a<=b<=10000,它们是某一个区间的开始值和结束值。
    【输出】
    第一行集合元素的个数,对于每一个区间都至少有一个整数属于该区间,且集合所包含元素数目最少。
    【样例输入】
    4
      3 6
      2 4
      0 2
      4 7
    【样例输出】
      2

    【算法分析】
    •算法模型:给n个闭区间[ai,bi], 在数轴上选尽量少的点,使每个区间内至少有一个点。
    •算法:首先按b1<=b2<=...<=bn排序。每次标记当前区间的右端点x,并右移当前区间指针,直到当前区间不包含x,再重复上述操作。
    •如下图,如果选灰色点,移动到黑色点更优。

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 struct section
     4 {
     5     int begin,end;
     6 };
     7 int cmp(const void *x,const void *y)
     8 {
     9     int ans1=(*(struct section *)x).end - (*(struct section *)y).end;
    10     if(ans1>0) return 1;
    11     else if(ans1<0) return -1;
    12     else 
    13     {
    14         ans1=(*(struct section *)y).begin - (*(struct section *)x).begin;
    15         return ans1;
    16     }
    17 }
    18 int main()
    19 {
    20     freopen("a.in","r",stdin);
    21     freopen("a.out","w",stdout);
    22     struct section *a;
    23     int *b;
    24     int n,i;
    25     int lastEnd;
    26     int count;
    27     
    28     scanf("%d",&n);
    29     a=(struct section *)malloc(n*sizeof(struct section));
    30     b=(int *)malloc(n*sizeof(int));
    31     
    32     for(i=0;i<n;i++)
    33     {
    34         scanf("%d%d",&a[i].begin,&a[i].end);
    35         b[i]=-1;
    36     }
    37     qsort(a,n,sizeof(struct section),cmp);
    38     
    39     lastEnd=-1;
    40     count=0;
    41     for(i=0;i<n;i++)
    42     {
    43         if(lastEnd>=a[i].begin) continue;
    44         count++;
    45         lastEnd=a[i].end;
    46         b[count-1]=lastEnd;
    47     }
    48     /*for(i=0;i<count;i++)
    49         printf("%d
    ",b[i]);*/
    50     printf("%d
    ",count);
    51     free(a);
    52     free(b);
    53     return 0;
    54 }
  • 相关阅读:
    drf—— 序列化组件
    drf—— RESTful API规范
    drf——APIView及其内部函数/类的源码分析
    drf—— drf的安装和使用
    226翻转二叉树
    51,N皇后
    557反转字符串中的单词III
    17.电话号码的字母组合
    459重复的子字符串
    419递增子序列
  • 原文地址:https://www.cnblogs.com/huashanqingzhu/p/6728713.html
Copyright © 2011-2022 走看看