区间调度问题

问题描述:

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

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

解决方法:

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

例题--【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;
}
相关推荐
EulerBlind17 分钟前
【机器学习】从KNN算法到图像风格迁移:原理与实践
人工智能·算法·机器学习
anscos39 分钟前
设计仿真 | 从物理扫描到虚拟检具:Simufact Welding革新汽车零部件检测
人工智能·算法·汽车·软件
tianchang1 小时前
JS 排序神器 sort 的正确打开方式
前端·javascript·算法
野犬寒鸦1 小时前
力扣hot100:字母异位词分组和最长连续序列(49,128)
java·数据结构·后端·算法·哈希算法
aini_lovee2 小时前
基于MATLAB的雷达系统设计中的信号处理程序
算法·3d
j_xxx404_2 小时前
数据结构:单链表的应用(力扣算法题)第一章
c语言·数据结构·算法·leetcode
百度Geek说2 小时前
ERNIE-4.5-VL:技术解密+应用实战,解锁多模态新场景!
算法
cur1es3 小时前
数据结构Java--8
java·数据结构·算法·散列表
tainshuai4 小时前
朴素贝叶斯:用 “概率思维” 解决分类问题的经典算法
算法·分类·数据挖掘