AcWing 905. 区间选点 (区间贪心问题)

AcWing 905. 区间选点

给定 N N N个闭区间 [ a i , b i ] [ai,bi] [ai,bi],请你在数轴上选择尽量少的点,使得每个区间内至少包含一个选出的点。

输出选择的点的最小数量。

位于区间端点上的点也算作区间内。

输入格式

第一行包含整数N,表示区间数。

接下来 N N N行,每行包含两个整数 a i , b i ai,bi ai,bi,表示一个区间的两个端点。

输出格式

输出一个整数,表示所需的点的最小数量。

数据范围

1 ≤ N ≤ 1 0 5 1 \leq N \leq 10^{5} 1N105
− 1 0 9 ≤ a i ≤ b i ≤ 1 0 9 -10^{9} \leq a_{i} \leq b_{i} \leq 10^{9} 109aibi109

思路

①将每个区间按右端点从小到大排序

②从前往后依次枚举每个区间

​ 如果当前区间中已经包含点,则直接pass

​ 否则,选择当前区间的右端点

证明上述方法是可行的:

c n t cnt cnt为所有可行解 a n s ans ans为可行解里的最小值 ∴ \therefore a n s < = c n t ans <= cnt ans<=cnt

c n t cnt cnt个互不相交的区间 至少要有 c n t cnt cnt个点 ∴ \therefore a n s > = c n t ans >= cnt ans>=cnt

∴ \therefore a n s = c n t ans = cnt ans=cnt

选最少的点 就要让一个点覆盖越多的区间 取右端点的话 就有更大的机会与后面的区间重合

#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
#include<stack>
#include<algorithm>
#include<vector>
#include<utility>
#include<deque>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define endl '\n'
#define eps 1e-6
inline int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
inline int lowbit(int x) { return x & -x; }


using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
const int N = 100010;


struct Range {
	int l, r;
}range[N];

bool cmp(struct Range a, struct Range b) {
	return a.r < b.r;
}

int main() {
	int n;cin >> n;
	
	for (int i = 0; i <= n;++i) {
		int l, r;
		scanf("%d%d", &l, &r);
		range[i] = { l,r };
	}
	sort(range, range + n, cmp);
	int res = 0, ed = -2e9;

	for (int i = 0;i < n;++i) {
		if (range[i].l > ed) {
			res++;
			ed = range[i].r;
		}
	}

	cout << res << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zzqwtc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值