区间调度问题

问题描述:

给定一组区间,每个区间都有一个开始时间和结束时间,目标是选择尽可能多的互不重叠的区间

区间调度实际上是在解决一组区间中,哪些区间可以同时选择而不起冲突的问题。

解决方法:

**贪心策略:**选择结束时间最早且与已选区间不重叠的区间。

例题--【CSES】Movie Festival

题目描述

In a movie festival n movies will be shown. You know the starting and ending time of each movie. What is the maximum number of movies you can watch entirely?

输入

The first input line has an integer n(1 ≤ n ≤ 2*105): the number of movies.

After this, there are n lines that describe the movies. Each line has two integers a and b(1 ≤ a < b ≤ 109): the starting and ending times of a movie.

输出

Print one integer: the maximum number of movies.

样例输入

3

3 5

4 9

5 8

样例输出

2

代码

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll N=200010;
struct movie{
	int a,b;
}m[N];
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin>>n;
	for (int i=1;i<=n;i++){
		cin>>m[i].a>>m[i].b;
	}
	sort(m+1,m+n+1,[](const movie &x,const movie &y){
		if (x.b==y.b)
		return x.a>y.a;
		return x.b<y.b;
	});
	int ans=0,end=0;
	for (int i=1;i<=n;i++){
		if (m[i].a>=end){
			ans++;
			end=m[i].b;
		}
	}
	cout<<ans;
}
相关推荐
bxlj_jcj14 分钟前
分布式ID方案、雪花算法与时钟回拨问题
分布式·算法
墨染点香15 分钟前
LeetCode 刷题【179. 最大数】
算法·leetcode·职场和发展
失忆已成习惯.19 分钟前
西农数据结构第四次实习题目参考
数据结构·算法·图论
kyle~19 分钟前
排序---堆排序(Heap Sort)
数据结构·c++·算法
yesyesido26 分钟前
3D在线魔方模拟器
科技·算法·3d·生活·业界资讯·交友·帅哥
是苏浙30 分钟前
蓝桥杯备战day1
算法
汉克老师31 分钟前
CCF-NOI2025第一试题目与解析(第二题、序列变换(sequence))
c++·算法·动态规划·noi
断剑zou天涯31 分钟前
【算法笔记】KMP算法
java·笔记·算法
程序员东岸33 分钟前
《数据结构——排序(下)》分治与超越:快排、归并与计数排序的终极对决
数据结构·c++·经验分享·笔记·学习·算法·排序算法
某林2121 小时前
在slam建图中为何坐标base_link,laser,imu_link是始终在一起的,但是odom 会与这位三个坐标在运行中产生偏差
人工智能·算法