区间调度问题

问题描述:

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

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

解决方法:

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

例题--【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;
}
相关推荐
Fuyo_11191 小时前
C++ AVL树保姆级详解:从平衡因子到四大旋转机制
java·c++·算法
jktantan1 小时前
每个节点 41 字节:把一棵百万节点树拆进 14 个 typed array
前端·javascript·vue.js·算法·typescript
揽星河..2 小时前
【C语言】猜数字游戏
c语言·算法·游戏
LabVIEW开发2 小时前
CTM-3 红外测温仪 + LabVIEW 温度怎么测?
算法·labview·测试·labview程序
纪念 2292 小时前
C++算法(六)
开发语言·c++·算法
Dumbness3 小时前
UIA 读微信群消息没有 id,怎么判断哪条是新的:后缀对齐在翻历史和撤回时整屏重报
python·算法
taka3 小时前
从 24x 到 141x:我用纯 Python 零依赖项目,扒开了 GPU 加速的性能黑洞
算法
UIU1144 小时前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
旖旎夜光4 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
像风一样自由20204 小时前
2.如何用FastAPI把一个Python算法封装成HTTP服务
python·算法·fastapi