题意:n头任性的牛,每头牛都要在自己的时间段里挤奶,问最少用多少个挤奶槽并输出每头牛所在的挤奶槽的编号(从1开始)
思路:目标明确,求最少用多少奶槽,并输出如何分配,明显区间贪心,找贪心的方向,就是对时间的最末端进行贪心。
简单来说,先把奶牛们的时间输入并按开始时间进行排序,然后依次把有序的时间段都放入堆中,在此过程中每次取出堆中末端时间最小的和当前放入堆的时间段进行比较,如果能放到同一个槽就放,反之开辟一个新槽,最终得出结果。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
struct Node{
int l;
int r;
int id; //第几头牛
int rk; //第几个槽
};
Node a[51000];
int n;
struct cmp{
bool operator()(Node &a,Node &b)
{
if(a.r != b.r)
return a.r > b.r;
else
return a.l > b.l;
}
};
int cmp1(Node a,Node b)
{
if(a.l != b.l)
return a.l < b.l;
return a.r < b.r;
}
int cmp2(Node a,Node b)
{
return a.id < b.id;
}
void input()
{
for(int i = 0 ; i < n ; i++){
cin >> a[i].l >> a[i].r;
a[i].id = i;
}
}
void solve()
{
int ans = 1;
sort(a,a+n,cmp1);
priority_queue <Node , vector<Node> , cmp > q;
a[0].rk = 1;
q.push(a[0]);
for(int i = 1 ; i < n ; i++)
{
Node t = q.top();
if( a[i].l > q.top().r )
{
a[i].rk = t.rk;
q.pop();
}
else{
a[i].rk = ++ans;
}
q.push(a[i]);
}
sort(a,a+n,cmp2);
cout << ans <<endl;
for(int i = 0 ; i < n ; i++)
cout<< a[i].rk <<endl;
}
int main()
{
#ifdef H_R
freopen("in.txt","r",stdin);
#endif // H_R
cin.tie(false);
ios::sync_with_stdio(false);
while(cin>>n)
{
input();
solve();
}
return 0;
}