POJ:1716 Integer Intervals(貪心)

Integer Intervals
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 14484   Accepted: 6153

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

Source

CEOI 1997

題目大意:

這道題的意思是
finds the minimal number of elements in a set containing at least two different integers from each interval.
0 1 2 3 4 5 6 7
-----           (0 to 2)
    -----       (2 to 4) 
      -------   (3 to 6)
        ------- (4 to 7)
包含上面集合的至少兩個元素的集合???
這裏需要的最小的集合是(1,2,4,5) or (1,2,4,6) 注意這裏的集合不需要是連續的數字,題目只要求出這種集合的元素個數,
所以輸出:4
解題思路:

先對所有區間按末端點排序(貪心)

取第i個區間的最後兩個元素SelemEelem

若第i+1個區間包含了這兩個元素,則跳到下一個區間所取的元素個數+0

若第i+1個區間只包含了這兩個元素中的一個(由於有序,所以必定是包含Eelem),則取第i+1個區間的最後一個元素,所取的元素個數+1。爲了方便下一區間的比較,更新SelemEelem的值,Selem變成此時的Eelem(貪心,儘量使數量少),Eelem變成當前區間的右端點。

若第i+1個區間沒有包含這兩個元素,則第i+1個區間的最後兩個元素,所取的元素個數+2。爲了方便下一區間的比較,更新SelemEelem的值,使他們爲當前V集合中最後的兩個元素。

 

Selem初始化爲第一個區間的最後倒數第2個元素

Eelem初始化爲第一個區間的最後的元素

所取的元素個數初始化爲2 (就是SelemEelem)



代碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; 
struct node
{
	int l,r;
}qu[10010];
bool cmp(struct node a,struct node b)
{
	return a.r<b.r;
}
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d%d",&qu[i].l,&qu[i].r);
	}
	sort(qu,qu+n,cmp);
	int z=qu[0].r-1,y=qu[0].r;
	int ans=2;//初始化 
	for(int i=1;i<n;i++)
	{
		if(z>=qu[i].l)//z,y在當前區間內,所以不更新 
		{
			continue;
		}
		if(z<qu[i].l&&y>=qu[i].l)//一個在區間內一個不在 
		{
			z=y;//貪心,使得數量儘量少 
			y=qu[i].r;
			ans++;
		}
		else//兩個都不在當前區間 
		{
			z=qu[i].r-1;
			y=qu[i].r;
			ans=ans+2;
		}
	}
	printf("%d\n",ans);
	return 0;
 } 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章