[C++]Stall ReservationsPOJ - 3190

Stall Reservations POJ - 3190

Stall Reservations:
Oh those picky N (1 <= N <= 50,000) cows! They are so picky that each one will only be milked over some precise time interval A…B (1 <= A <= B <= 1,000,000), which includes both times A and B. Obviously, FJ must create a reservation system to determine which stall each cow can be assigned for her milking time. Of course, no cow will share such a private moment with other cows.

Help FJ by determining:
The minimum number of stalls required in the barn so that each cow can have her private milking period
An assignment of cows to these stalls over time
Many answers are correct for each test dataset; a program will grade your answer.

输入格式:
Line 1: A single integer, N

Lines 2…N+1: Line i+1 describes cow i’s milking interval with two space-separated integers.
输出格式:
Line 1: The minimum number of stalls the barn must have.

Lines 2…N+1: Line i+1 describes the stall to which cow i will be assigned for her milking period.

输入:
5
1 10
2 4
3 6
5 8
4 7
输出:
4
1
2
3
2
4

题目大意:
这里有N只 (1 <= N <= 50,000) 挑剔的奶牛! 他们如此挑剔以致于必须在[A,B]的时间内产奶(1 <= A <= B <= 1,000,000)当然, FJ必须为他们创造一个决定挤奶时间的系统.当然,没有牛想与其他奶牛分享这一时光

帮助FJ做以下事:
使每只牛都有专属时间的最小牛棚数
每只牛在哪个牛棚
也许有很多可行解。输出一种即可,采用SPJ

解题分析:
以最短结束时间排序优先队列,每个元素有牛棚号与结束时间
如果该头牛的开始时间小于队头的结束时间,则需要新增一个牛棚
反之,如果该头牛的开始时间大于队头的结束时间,则表示可以与其共用一个牛棚,于是弹出,并将该头牛与牛棚号加入队列
过程中将结果存入pos数组中。pos[i]表示第i头牛所在的牛棚号。

AC代码:

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;

int n;

struct ST{
	int l, r;
	int i;
};

struct node{
	int no;
	int end;
	
	// 以畜栏结束时间早排序 
	bool operator < (const node & c) const{
		return end > c.end;
	}
	
	// 构造函数
	node(int no, int end):no(no), end(end){}
};

int cmp(ST a, ST b){
	return a.l < b.l;
}

ST mp[50010];
int pos[1000010];

priority_queue<node> q;

int main(){
	cin>>n;
	
	for(int i = 0; i<n; i++){
		cin>>mp[i].l>>mp[i].r;
		mp[i].i = i;
	}
	sort(mp, mp+n, cmp);
	int res = 0;
	for(int i = 0; i<n; i++){
		if(q.empty()){
			++res;
			pos[ mp[i].i] = res;
			q.push(node(res, mp[i].r));
		}
		else {
			node nod = q.top();
			if(nod.end < mp[i].l){
				q.pop();
				pos[mp[i].i] = nod.no;
				q.push(node(nod.no, mp[i].r));
			}
			else {
				++res;
				pos[mp[i].i] = res;
				q.push(node(res, mp[i].r));
			}	
		}
	}
	
	cout<<res<<endl;
	for(int i = 0; i<n; i++){
		cout<<pos[i]<<endl;
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值