区间调度问题

问题描述:

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

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

解决方法:

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

例题--【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;
}
相关推荐
rengang6617 小时前
09-随机森林:介绍集成学习中通过多决策树提升性能的算法
人工智能·算法·随机森林·机器学习·集成学习
CoovallyAIHub17 小时前
量子计算迎来诺奖时刻!谷歌赢麻了
深度学习·算法·计算机视觉
法拉第第18 小时前
caffine概率统计算法之Count-Min Sketch
算法
法拉第第18 小时前
淘汰策略之tinyLFU
算法
mit6.82418 小时前
[Tongyi] 工具集成 | run_react_infer
人工智能·深度学习·算法
闻缺陷则喜何志丹18 小时前
【C++贪心】P8769 [蓝桥杯 2021 国 C] 巧克力|普及+
c++·算法·蓝桥杯·洛谷
杨小码不BUG18 小时前
灯海寻踪:开灯问题的C++精妙解法(洛谷P1161)
c++·算法·数学建模·位运算·浮点数·信奥赛·csp-j/s
杨小码不BUG18 小时前
心痛之窗:滑动窗口算法解爱与愁的心痛(洛谷P1614)
开发语言·c++·算法·滑动窗口·csp-j/s·多维向量
咖啡啡不加糖19 小时前
贪心算法详解与应用
java·后端·算法·贪心算法
一只鱼^_20 小时前
力扣第470场周赛
数据结构·c++·算法·leetcode·深度优先·动态规划·启发式算法