区间调度问题

问题描述:

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

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

解决方法:

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

例题--【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;
}
相关推荐
我不会起名字3222 分钟前
一天一道力扣Hot100(36):深度优先算法---组合总和
数据结构·c++·后端·python·算法·go
虚无的纽扣29 分钟前
【力扣刷题】第三天:有效三角形的个数、快乐数
算法·排序算法
tiger86533 分钟前
大语言模型面试和题解,Context Engineering 怎么做?长 Prompt、动态上下文与 Memory 管理
人工智能·深度学习·算法·语言模型·自然语言处理·面试·nlp
不会就选b1 小时前
算法日常・每日刷题--<贪心>17
算法
6Hzlia4 小时前
【Classic 150 刷题计划】 LeetCode 205. 同构字符串 | C++ 双向绑定与哈希表映射
c++·算法·leetcode
有点。10 小时前
C++03阶段练习(练习题)
数据结构·算法·图论
周末也要写八哥11 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸12 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp12 小时前
KV Cache 解析
java·算法
liliangcsdn12 小时前
IVOL与偏度因子的对比测量分析
算法