题意给n个区间,放在一个数轴上,区间交不能超过k,问最多能放多少个区间?
思路我一开始是用一个队列去模拟了一下,排个序,每次放进去右端点,然后用左端点看是不是能弹出去之前的右端点。。。卡在第6个点。。。就不对了。。。
正解先按右端点小,左端点小去排序,先放k个,原理就是,尽量不让空间去浪费,在a.r < b.l的情况下,先放了a,该放b了,找和b.l左边最接近的区间去放,尽量空间不浪费。
lower_bound是大于等于他的第一个值,但是咱们找的是小于等于他的最后一个值,骚操作来了 应该给他变成负数。就很不错。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef long long LL;
const int MaxN = 1e5;
int n , k , p[MaxN + 5];
struct node{
int l , r;
}a[MaxN + 5];
set<pair<int , int> > st;
bool cmp(node x , node y)
{
if(x.r == y.r) return x.l < y.l;
return x.r < y.r;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(~scanf("%d %d",&n , &k)){
for(int i = 1 ; i <= n ; i++){
scanf("%d %d",&a[i].l , &a[i].r);
}
sort(a + 1 , a + 1 + n , cmp);
st.clear();
for(int i = 1 ; i <= k ; i++) st.insert(make_pair(0 , i));
int ans = 0;
for(int i = 1 ; i <= n ; i++){
set <pair<int , int> > :: iterator it = st.lower_bound(make_pair(-a[i].l , 0));
if(it != st.end()){
int tmp = (*it).second;
st.erase(it);
st.insert(make_pair(-a[i].r , tmp));
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}