NOI 4.6 贪心 718: Integer Intervals

题目来源:http://noi.openjudge.cn/ch0406/718/

718: Integer Intervals

总时间限制1000ms 内存限制65536kB

描述

An integer interval [a,b], a < b, is a set of all consecutiveintegers beginning with a and ending with b. 
Write a program that: finds the minimal number of elements in a set containingat least two different integers from each interval.

输入

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, bseparated by a single space, 0 <= a < b <= 10000. They are thebeginning and the end of an interval.

输出

Output the minimal number of elements in a set containing atleast two different integers from each interval.

样例输入

4
3 6
2 4
0 2
4 7

样例输出

4

来源

CEOI 1997

 -----------------------------------------------------

思路

题意:求最小的整数集合,使得每个区间中都有至少两个数在该集合中。

思路:将区间按末端升序排列。用s1,s2表示在每个区间取的两个数(s1<s2). s1,s2初始化为第一个区间的最后两个数。之后循环其余(n-1)个集合,如果该集合的始端小于等于s1, 则不用改变s1,s2,结果数不变;若该集合的始端大于s1小于等于s2, s1=s2, s2变为当前集合的末端,结果数+1;若该集合的始端大于s2,s1,s2为当前集合的最后两个数,结果数+2

-----------------------------------------------------

代码

#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;

struct interval {
	int a,b;

	interval(){}
	interval(int aa, int bb): a(aa),b(bb){}

	bool operator< (const interval &bint)
	{
		return b < bint.b;
	}
};

const int NMAX = 10005;
interval vec[NMAX] = {};

int main()
{
#ifndef ONLINE_JUDGE
	ifstream fin ("0406_718.txt");
	int n,i,a,b,s1,s2,ans=0;
	fin >> n;
	for (i=0; i<n; i++)
	{
		fin >> a >> b;
		interval myint(a,b);
		vec[i] = myint;
	}
	fin.close();
	sort(vec, vec+n);
	s1 = vec[0].b-1;
	s2 = vec[0].b;
	ans = 2;
	for (i=1; i<n; i++)
	{
		interval myint = vec[i];
		if (myint.a <= s1)
		{
			continue;
		}
		else if (myint.a<=s2)
		{
			ans++;
			s1 = s2;
			s2 = myint.b;
		}
		else
		{
			ans += 2;
			s1 = myint.b-1;
			s2 = myint.b;
		}
	}
	cout << ans;
	return 0;
#endif
#ifdef ONLINE_JUDGE
	int n,i,a,b,s1,s2,ans=0;
	cin >> n;
	for (i=0; i<n; i++)
	{
		cin >> a >> b;
		interval myint(a,b);
		vec[i] = myint;
	}
	sort(vec, vec+n);
	s1 = vec[0].b-1;
	s2 = vec[0].b;
	ans = 2;
	for (i=1; i<n; i++)
	{
		interval myint = vec[i];
		if (myint.a <= s1)
		{
			continue;
		}
		else if (myint.a<=s2)
		{
			ans++;
			s1 = s2;
			s2 = myint.b;
		}
		else
		{
			ans += 2;
			s1 = myint.b-1;
			s2 = myint.b;
		}
	}
	cout << ans;
	return 0;
#endif
}


猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/80835375
4.6