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\n",sum);
46     return 0;
47 }
View Code

 



posted on 2013-11-06 20:40  straw_berry  阅读(268)  评论(0编辑  收藏  举报