先按照结束时间进行排序,取第一个节日的结束时间作为当前时间,然后从第二个节日开始搜索,如果下一个节日的开始时间大于当前的时间,那么就参加这个节日,并更新当前时间
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e4+5;
struct node {
int be, ed; // 开始时间和结束时间
}nds[maxn];
bool cmp(node x, node y) {
return x.ed < y.ed;
}
int main() {
int n; cin >> n;
for (int i = 1; i <= n; ++i) {
int t, l; cin >> t >> l;
nds[i].be = t, nds[i].ed = t+l-1;
}
// 按照节日的结束时间从小到大进行排序
sort(nds+1,nds+1+n,cmp);
// 取第一个节日的结束时间作为当前的时间,答案赋值为1
int now_time = nds[1].ed, ans = 1;
for (int i = 2; i <= n; ++i) {
// 如果下一个节日的开始时间大于当前的时间,那么参加这个节日
// 因为是按照结束时间进行排序的,所以参加这个节日肯定最优
if (nds[i].be > now_time) {
// 答案加一
ans++;
// 更新当前时间
now_time = nds[i].ed;
}
}
cout << ans << endl;
return 0;
}
原文:https://www.cnblogs.com/wstong/p/12823194.html