poj1716 Integer Intervals

poj1716  Integer Intervals

时空限制    1000ms/10000K

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


分析

先对所有区间按末端点升序排序
x初始化为第一个区间的最后倒数第2个元素
y初始化为第一个区间的最后的元素
所取的元素个数ans初始化为2 (就是x和y)
对第i(2<=i<=n)个区间分析是否包含x和y
若第i个区间包含了这两个元素(即a[i].str<=x),则跳到下一个区间所取的元素个数+0。(这种情况后面代码没有反应)
若第i个区间只包含了这两个元素中的一个(由于有序,所以必定是包含y,即a[i].str>x && a[i].str<=y),则取第i个区间的最后一个元素,所取的元素个数+1。为了方便下一区间的比较,更新x和y的值,使x为第i-1个区间最后一个元素,也就是y,y为第i个区间最后一个元素。
若第i个区间没有包含这两个元素(即a[i].str>y),则第i个区间的最后两个元素,所取的元素个数+2。为了方便下一区间的比较,更新x和y的值,使他们为当前V集合中最后的两个元素。

代码

#include<iostream>
#include<algorithm>
using namespace std;
const int N = 10005;
struct node{
	int str,end;
	bool operator < (const node &x)const{
		return end<x.end;
	}
};
node a[N];

int main(){
	int n;
	cin>>n;
	for (int i=1; i<=n; i++) cin>>a[i].str>>a[i].end;
	sort(a+1,a+n+1);
	int ans=2,x=a[1].end-1,y=a[1].end;
	for (int i=2; i<=n; i++)
		if (a[i].str>x && a[i].str<=y) ans++,x=y,y=a[i].end;
		else if (a[i].str>y) ans+=2,x=a[i].end-1,y=a[i].end;
	cout<<ans<<endl;
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值