题目背景
快 noip 了,yyy 很紧张!
题目描述
现在各大 oj 上有 n n n 个比赛,每个比赛的开始、结束的时间点是知道的。
yyy 认为,参加越多的比赛,noip 就能考的越好(假的)。
所以,他想知道他最多能参加几个比赛。
由于 yyy 是蒟蒻,如果要参加一个比赛必须善始善终,而且不能同时参加 2 2 2 个及以上的比赛。
输入格式
第一行是一个整数 n n n ,接下来 n n n 行每行是 2 2 2 个整数 a i , b i a_{i},b_{i} ai,bi ( a i < b i a_{i}<b_{i} ai<bi ),表示比赛开始、结束的时间。
输出格式
一个整数最多参加的比赛数目。
样例 #1
样例输入 #1
3
0 2
2 4
1 3
样例输出 #1
2
提示
对于 20 % 20\% 20% 的数据, n ≤ 10 n \le 10 n≤10。
对于 50 % 50\% 50% 的数据, n ≤ 1 0 3 n \le 10^3 n≤103。
对于 70 % 70\% 70% 的数据, n ≤ 1 0 5 n \le 10^{5} n≤105。
对于 100 % 100\% 100% 的数据, 1 ≤ n ≤ 1 0 6 1\le n \le 10^{6} 1≤n≤106 , 0 ≤ a i < b i ≤ 1 0 6 0 \le a_{i} < b_{i} \le 10^6 0≤ai<bi≤106。
解题思路:
尽量选择结束时间更早的比赛,因为可以留出更多的时间
实现代码如下
#include <iostream>
#include <algorithm>
using namespace std;
const int max_n = int(1e6);
struct competition {
public:
int start;
int end;
};
competition competitions[max_n];
competition* end_first[max_n] = { NULL };
int main() {
int current_t = 0, n, sum = 0;
cin >> n;
for (int i = 0; i < n; i++) {//读入比赛起止时间
cin >> competitions[i].start >> competitions[i].end;
end_first[i] = &competitions[i];
}
sort(end_first, end_first + n, [](competition* e_f_1, competition* e_f_2) {//依照结束时间排序
return e_f_1->end < e_f_2->end;
});
for (int i = 0; i < n; i++) {//搜索最大参赛量
if (current_t <= end_first[i]->start) {
sum++;
current_t = end_first[i]->end;
}
}
cout << sum << endl;
return 0;
}