最近一直在练习区间贪心问题, 发现这种问题在比赛中出现的频率蛮高的, 不过一般也都是水题
这是一道基础的区间覆盖问题, 我开始最大的误区就是在排序上, 一直执着于按开始时间从小到大排, 而正确的排序方法应该是按结束时间从小到大排, 同时考虑结束时间相等时按开始时间从小到大排
之后就每次取不相交的就好了
//会场安排问题 区间贪心
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(n));
typedef long long LL;
const LL maxn = 10010;
struct node{
int b, e;
}act[maxn];
bool cmp(const node a, const node b)
{
if(a.e == b.e) return a.b < b.b; //结束时间相等则先开始的在前面(总时间短)
return a.e < b.e; //最早结束的在前面
}
int T, n;
int solve()
{
int ans = 0;
sort(act+1, act+1+n, cmp);
int now = -1000;
for(int i = 1; i <= n; i++){
//从左到右遇到不相交的时间段就选
if(act[i].b > now) ans++, now = act[i].e;
}
return ans;
}
int main()
{
cin >> T;
while(T--){
ms(act, 0);
cin >> n;
for(int i = 1; i <= n; i++)
cin >> act[i].b >> act[i].e;
cout << solve() << endl;
}
return 0;
}