POJ 1716 Integer Intervals

来源:互联网 发布:重庆网络推广软件 编辑:程序博客网 时间:2024/06/10 22:09

题目链接:http://poj.org/problem?id=1716

题目:

Integer Intervals
Time Limit: 1000MS
Memory Limit: 10000KTotal Submissions: 12788
Accepted: 5413

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

Source

CEOI 1997

题目大意:给出n个区间,选出几个数字组成一个集合,使得每个区间至少有两个数字在这个集合里面,求这个集合的最少数字个数。用贪心来做。对每个区间的最右端的元素按从小到大进行排序,由于区间是一个整体,这里需要把每个区间定义成一个结构体,用sort函数进行排序。多加一个比较方法,比如:
 int cmp(const node &a,const node &b){
return a.y < b.y ;
}
然后定义一个arr数组来区分是否被选中成为所求集合中的元素,初始化为0,选中则标记为1。开始的时候先选择排好序后的第一个区间的最后两个数,添加到我们要求的集合中,并把它们对应的标记变为1,即 arr[a[0].y-1] = arr[a[0].y] = 1; 定义p 来记录下一个区间中与前一个区间中相同元素的个数,定义count为所求集合的元素个数,初始化为2。若p==0,则表示该区间与前一个区间没有相同的元素,则取该区间的最后两个元素,添加进所求集合中,并把对应的标记arr改为1,同时count加2;若p==1,表示该区间与前一个区间有一个元素相同,则取该区间的最后一个元素添加进所求集合中,并修改其标记为1,同时count加1;若p==2,表示该区间与前一个区间有两个元素相同,则无需再从该区间取元素添加进所求元素中,则break,直接退出内层循环。
以下为代码,已AC:
 
#include<stdio.h>#include<algorithm>#include<string.h>#define N 10005using namespace std;int arr[N]; struct node{int x;int y;}a[N];int cmp(const node &a,const node &b){return a.y<b.y;}int main(){int n,i,j,p,count=2;   memset(arr,0,sizeof(arr));scanf("%d",&n);for(i=0;i<n;i++){scanf("%d %d",&a[i].x,&a[i].y);}sort(a,a+n,cmp);arr[a[0].y-1]=arr[a[0].y]=1;for(i=1;i<n;i++){p=0;for(j=a[i].x;j<=a[i].y;j++){if(arr[j]){p++;}if (p==2) break;}if(p==0){arr[a[i].y-1]=arr[a[i].y]=1;count+=2;}else if(p==1){arr[a[i].y]=1;count++;}}printf("%d\n",count);return 0;}
请广大读者指正~

0 0
原创粉丝点击