题目概况
题目链接: https://www.luogu.com.cn/problem/P1803
难度: 普及-
题目分析
简化题目: 想成n条线段,最多有多少条不重合区间
涉及知识点: 贪心算法
解题思路:
如上面的简化题目,我们想象成线段后,每场比赛的开始时间是左端点,结束时间是右端点。
我们先按照右端点升序排序,再选择线段。在选择过程中,使用一个变量来记录上次选了的线段的右端点,当前的左端点不能大于它。
代码拆解
无
完整代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iomanip>
using namespace std;
const int MAXN = 1e6 + 5;
int n;
int ans = 1;
struct node {
int start;
int end;
}a[MAXN];
bool cmp (node x, node y) {
return x.end < y.end;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i].start >> a[i].end;
}
sort(a + 1, a + n + 1, cmp);
int last_b = a[1].end;
for (int i = 2; i <= n; i++) {
if (a[i].start >= last_b) { //如果这场的开始时间大于前一面参加了的一场的结束时间就选
ans++;
last_b = a[i].end;
}
}
cout << ans << endl;
return 0;
}

该博客主要解析了洛谷P1803题目的解题思路,将其简化为考虑不重合线段的最大数量问题。通过贪心算法,将线段按右端点升序排序,并确保新选择的线段左端点不超过已选线段的右端点,从而实现最大不重合线段数的选择。
4294

被折叠的 条评论
为什么被折叠?



