V - 22

本文介绍了一个寻找最少元素数量的问题,这些元素至少包含每个指定区间内的两个不同整数。通过将区间按结束点排序并采用贪心算法,文章提供了一种有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
题意:
找一个数组,使数组里至少有两个整数属于间隔,每个间隔里的两个数都在这个数组

分析:
贪心,先按照b从小到大排序,在将数组里的数跟后面的间隔前两个比较

代码:

#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
	int x;
	int y;
}b[100001];
bool cmp(node a,node b)
{
	return a.y<b.y;
}
int main()
{
	int n,j,i,m[10001];
	scanf("%d",&n);
	for(i=0;i<n;i++)
	scanf("%d%d",&b[i].x,&b[i].y);
	sort(b,b+n,cmp);
	m[0]=b[0].y-1;
	m[1]=b[0].y;
	j=0;
	for(i=1;i<n;i++)
	{
	  if(b[i].x<=m[j]&&m[j+1]<=b[i].y)
	     {
		continue;
	     }
	   if(m[j+1]>=b[i].x&&m[j]<b[i].x)
	{
	   m[j+2]=b[i].y;
	   j=j+1;
	}
	    if(m[j+1]<b[i].x)
	{
	   
	   m[j+2]=b[i].y-1;
	   m[j+3]=b[i].y;	
	   j=j+2;
	}
	}
	printf("%d\n",j+2);
	
}
感受:
挺简单的,就是题意一开始没有读懂。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值