题目描述 现在各大oi上有n个比赛,每个比赛的开始、结的时间点是知道的yyy 认为,参加越多的比赛,noip 就能考的越好(假的)。 所以,他想知道他最多能参加几个比赛 由于yyy 是药,如果要参加一个比赛必须善始善终,而且不能同时参加2个及以上的比赛 输入格式 第一行是一个整数n,接下来n行每行是2个整数a(a,表示比赛开始、结束的时间 输出格式 一个整数最多参加的比赛数目
这道题可以用贪心算法来解决,具体方法如下:
首先按照结束时间将所有比赛排序,结束时间早的排在前面。
从第一个比赛开始,依次判断每个比赛能否参加。如果当前比赛的开始时间晚于上一个比赛的结束时间,则可以参加。否则,不能参加。
记录下能参加的比赛数目,最后输出即可。
#include <algorithm>
#include <iostream>
#include <vector>using namespace std;int main() {int n;cin >> n;vector<pair<int, int>> matches;for (int i = 0; i < n; i++) {int start, end;cin >> start >> end;matches.push_back(make_pair(start, end));}sort(matches.begin(), matches.end(),[](const pair<int, int> &a, const pair<int, int> &b) {return a.second < b.second; // 按结束时间升序排序});int count = 0; // 参加比赛的数目int end_time = 0; // 上一个比赛的结束时间for (const auto &match : matches) {if (match.first >= end_time) { // 可以参加该比赛count++;end_time = match.second;}}cout << count << endl;return 0;
}