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
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值