【Poj】-1716-Integer Intervals(贪心)

Integer Intervals
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 14480 Accepted: 6151

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个区间每个区间至少两个数在集合内,求集合元素最小值


题解:将已知区间按照右端点升序排列。

数目ans最小为 2

取第一个区间的最后两个值作为st,ed.这样可以保证和后面的集合有最大交集,后面类似。

然后与后面区间比较考虑 

1 st,ed都在后面区间范围里,ans不变,继续

2 ed在后面区间里,ans++

3 都不在 ans+=2

最后考虑st ed的更新

#include <cstdio>  
#include <algorithm>  
using namespace std;  
struct node
{
	int l,r;	
}a[10010];
bool cmp(node x,node y)
{
	if(x.r!=y.r)
		return x.r<y.r;
	return x.l>y.l;
}
int main()  
{  
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d%d",&a[i].l,&a[i].r);
	sort(a+1,a+1+n,cmp);
	int ans=2;
	int st=a[1].r-1,ed=a[1].r;
	for(int i=2;i<=n;i++)
	{
		if(st>=a[i].l)		//包含在下一个区间 
			continue;
		else if(st<a[i].l&&ed>=a[i].l)	//st,ed仅一个在下一个区间里,只可能是ed 
		{
			ans++;			//在下一个区间取一个赋值给 ed ,ans++ 
			st=ed;			//更新 st 
			ed=a[i].r; 		//取区间的最后一个,这样才会最优(尽可能和后面区间有交集) 
		}
		else
		{
			ans+=2;		//都不包含,取两个,分别是 st ed 
			st=a[i].r-1;
			ed=a[i].r;
		}
	}
	printf("%d\n",ans);
    return 0;  
}  



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值