区间问题选择不相交区间

博客内容涉及两种不同的不相交区间选择算法的C++实现。第一种按左端点从大到小排序,然后根据右端点更新不相交区间计数;第二种则按右端点从小到大排序,同样更新不相交区间计数。两种方法都通过交换确保输入区间正确排序,并使用`sort`函数进行区间排序。

区间问题选择不相交区间

https://blog.youkuaiyun.com/qq_40073459/article/details/86636963?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.channel_param

此处存在输入数据没有交换的问题:

#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn = 110;

struct Inteval {
	int x, y;
}I[maxn];

bool cmp(Inteval a, Inteval b)
{
	if (a.x != b.x) return a.x > b.x;//按左端点从大到小排序
	else return a.y < b.y;//左端点相同时按右端点从小到大排序
}
int main()
{
	int n;
	while (scanf_s("%d", &n), n != 0)
	{
		for (int i = 0; i < n; i++)
		{
			scanf_s("%d%d", &I[i].x, &I[i].y);
			if (I[i].x > I[i].y) {//记得交换输入数据的位置
				int temp = I[i].x;
				I[i].x = I[i].y;
				I[i].y = temp;
			}
		}
		sort(I, I + n, cmp);//把区间排序

		int ans = 1, lastX = I[0].x;
		for (int i = 1; i < n; i++)
		{
			if (I[i].y <= lastX) {//如果该区间右端点在lastX左侧
				lastX = I[i].x;//以I[i]作为新选中的区间
				ans++;//不相交区间加1
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 110;
struct Inteval {
	int x, y;
}I[maxn];
bool cmp(Inteval a, Inteval b)
{
	if (a.y != b.y) return a.y < b.y;//按右端点从小到大排序
	else return a.x > b.x;
}
int main()
{
	int n;
	while (scanf("%d", &n), n != 0)
	{
		for (int i = 0; i < n; i++)
		{
			scanf("%d%d", &I[i].x, &I[i].y);
			if (I[i].x > I[i].y) {//记得交换输入数据的位置
				int temp = I[i].x;
				I[i].x = I[i].y;
				I[i].y = temp;
			}
		}
		sort(I, I + n, cmp);
		int ans = 1, lastY = I[0].y;
		for (int i = 1; i < n; i++)
		{
			if (I[i].x >= lastY) {
				lastY = I[i].y;
				ans++;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}

https://blog.youkuaiyun.com/liusuangeng/article/details/38519403?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值