区间调度问题

问题描述:

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

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

解决方法:

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

例题--【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;
}
相关推荐
恣艺13 分钟前
LeetCode 124:二叉树中的最大路径和
算法·leetcode·职场和发展
weisian15129 分钟前
力扣经典算法篇-42-矩阵置零(辅助数组标记法,使用两个标记变量)
算法·leetcode·矩阵
恣艺42 分钟前
LeetCode 123:买卖股票的最佳时机 III
算法·leetcode·职场和发展
geoyster1 小时前
20250802-102508010-CP
算法
Q741_1471 小时前
优选算法 力扣 202.快乐数 快慢双指针 解决带环问题 C++解题思路 每日一题
c++·算法·leetcode·快慢双指针·环形问题
DONG9131 小时前
Python 中的可迭代、迭代器与生成器——从协议到实现再到最佳实践
开发语言·汇编·数据结构·python·算法·青少年编程·排序算法
GeekPMAlex2 小时前
RAG 02 多模态检索 多维主键
算法
CoovallyAIHub2 小时前
只有2MB,却能跑满277FPS?专为无人机小目标打造!
深度学习·算法·计算机视觉
金宗汉2 小时前
文明存续的时间博弈:论地球资源枯竭临界期的技术突围与行动紧迫性
大数据·人工智能·笔记·算法·观察者模式
YLCHUP2 小时前
题解:P4447 [AHOI2018初中组] 分组
开发语言·数据结构·c++·经验分享·算法·贪心算法·抽象代数