题意
有 个区间,将他们分为几组使他们互不相交,求最小组数
思路
对于每个区间,根据他们的左端点非降序排序。
我们可以贪心的处理每个区间,如果有一组可以放入就放入,否则新分一个组。
代码
#include <bits/stdc++.h>
#define ll long long
#define min(a, b) (a < b ? a : b)
#define max(a, b) (a > b ? a : b)
using namespace std;
ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; }
void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); return; }
const int N = 2e5 + 3;
int n;
int c, ans[N];
struct R{
int a, b, id;
bool operator < (const R &s) const{
if(s.a == a) return s.b > b;
return s.a > a;
}
}a[N];
struct P{
int x, id;
bool operator < (const P &s) const{
return s.x < x;
}
};
priority_queue <P> q;
int main(){
n = read();
for(int i = 1; i <= n; i ++){
a[i] = {read(), read(), i};
}
sort(a + 1, a + 1 + n);
for(int i = 1; i <= n; i ++){
if(q.empty() || q.top().x >= a[i].a) q.push({a[i].b, ++ c}), ans[a[i].id] = c;
else ans[a[i].id] = q.top().id, q.push({a[i].b, q.top().id}), q.pop();
}
write(c), putchar('\n');
for(int i = 1; i <= n; i ++){
write(ans[i]), putchar(' ');
}
return 0;
}