POJ
来源:互联网 发布:讲课视频的软件 编辑:程序博客网 时间:2024/05/16 15:36
Integer Intervals
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 14913 Accepted: 6310
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.
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个区间,让求一个集合,每个区间至少有两个整数包含在这个集合内,求集合最少包含几个元素。
题解:
贪心。先将集合按照右边界从小到大排序。取两个变量first,second(first < second)分别为当前区间取的两个值。优先右取,这样可以保证first和second可以包含在尽量多的区间内。不断维护first和second的值。如果当前区间的左边界大于second,就需要在本区间内重新取两个值,sum+2;如果左边界小于等于second且大于first,则将second赋给first,second取右边界(保证first < second),sum+1;如果左边界小于first,则不需要改变first和second的值。
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;struct node{ int left,right;}p[10005];bool cmp(node a,node b){ return a.right<b.right;}int main(){ int n; while(~scanf("%d",&n)) { for(int i=0;i<n;i++) scanf("%d%d",&p[i].left,&p[i].right); sort(p,p+n,cmp); int first=p[0].right-1,second=p[0].right,sum=2; for(int i=1;i<n;i++) { if(p[i].left>second) { sum+=2; second=p[i].right; first=second-1; } else if(p[i].left<=second && p[i].left>first) { sum++; first=second; second=p[i].right; } } printf("%d\n",sum); } return 0;}
阅读全文
0 0
- POJ
- poj
- POJ
- POJ
- poj
- poj
- POJ
- POJ
- poj
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- C语言中 A||B&&C的执行顺序是怎么的?
- 机器学习随笔一:数据不平衡问题
- 每日英语阅读(十)
- Eclipse和PyDev搭建完美Python开发环境
- How to use struts2 for program development?
- POJ
- 【算法】10亿int型数,统计只出现一次的数
- 5-16 求符合给定条件的整数集 (15分
- MySQL的安装
- QT编程之区分点击和双击事件
- leetcode-88
- servlet之filter知识
- 浅谈Python中对象拷贝
- 精通Jquery,JavaScript详解及回顾(3)