POJ3190 Stall Reservations (贪心+优先队列)

题目链接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;
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值