题目链接http://poj.org/problem?id=3190
题目大意:有n头牛,每头牛都必须在[l,r]这个区间内才能够产生牛奶,当两头牛生产奶的区间不相交时,能够共用一台机器,否则就要换一台机器。
思路:首先把每头牛生产牛奶的区间按照左端点从小到大排序,又因为数据量较大,所以选择用优先队列来维护。把优先队列里的元素按照区间右端点进行排序,结束的越早优先级越高。首先把开始最早的区间入队列,取队列头元素设为no,如果no.l > p[i].r,则说明两区间不相交,可以共用一台机器,出队首区间,否则加一台新的机器。
附优先队列讲解http://blog.csdn.net/ac_gibson/article/details/44200411
AC代码如下:
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 50005;
int n;
struct node{
int l,r,index,val;
friend bool operator <(node A, node B){
if(A.r == B.r)
return A.l > B.l;
return A.r > B.r;
}
}p[maxn];
bool cmp(node A, node B){
if(A.l == B.l)
return A.r < B.r;
return A.l < B.l;
}
void solved(){
sort(p,p+n,cmp);
priority_queue<node> q;
p[p[0].index].val = 1;
q.push(p[0]);
int k = 1;
for(int i = 1; i < n; i ++){
node no = q.top();
if(!q.empty() && no.r < p[i].l){
p[p[i].index].val = p[no.index].val;
q.pop();
q.push(p[i]);
}
else{
p[p[i].index].val = ++ k;
q.push(p[i]);
}
}
printf("%d\n",k);
for(int i = 0; i < n; i ++)
printf("%d\n",p[i].val);
}
int main(){
while(~scanf("%d",&n)){
for(int i = 0; i < n; i ++){
scanf("%d%d",&p[i].l,&p[i].r);
p[i].index = i;
}
solved();
}
return 0;
}