P2859 [USACO06FEB]Stall Reservations S(区间问题,堆)

题目描述

约翰的N(l<N< 50000)头奶牛实在是太难伺候了,她们甚至有自己独特的产奶时段.当 然对于某一头奶牛,她每天的产奶时段是固定的,为时间段A到B包括时间段A和时间段B.显然,约翰必须开发一个调控系统来决定每头奶牛应该被安排到哪个牛棚去挤 奶,因为奶牛们显然不希望在挤奶时被其它奶牛看见.
约翰希望你帮他计算一下:如果要满足奶牛们的要求,并且每天每头奶牛都要被挤过奶,至少需要多少牛棚 •每头牛应该在哪个牛棚被挤奶。如果有多种答案,你只需任意一种即可。

输入格式

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

题目分析

就是一个简单的区间摆放问题。
我们可以把区间按左端点进行排序,然后用堆来维护每个棚的最后一个区间的右端点的位置

1、如果堆为空或者堆顶元素的位置小于等于当前区间的左端点,则开一个新棚来放这个区间。

2、如果堆顶元素位置大于当前区间的左端点,则说明当前区间可以放入堆顶的棚中。

代码如下
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>
#include <iomanip>
#define LL long long
#define ULL unsigned long long
#define PII pair<int,int>
#define PLL pair<LL,LL>
#define PDD pair<double,double>
#define x first
#define y second
using namespace std;
const int N=1e5+5,mod=998244353;
struct Node{
	int id,l,r;
	bool operator< (const Node a)const
	{ return l<a.l; }
}a[N];
int ans[N];
priority_queue<PII,vector<PII>,greater<PII> > heap;		//小根堆
void newInsert(int i,int& cnt)			//开一个新棚储存第i个区间
{
	heap.push({a[i].r,a[i].id});
	cnt++;
	ans[a[i].id]=cnt;
}
int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		int l,r;
		cin>>l>>r;
		a[i]={i,l,r};
	}
	sort(a+1,a+1+n);				//将区间按左端点进行排序
	int cnt=0;						//记录棚数
	for(int i=1;i<=n;i++)
	{
		if(heap.empty()) newInsert(i,cnt);		//情况1
		else 
		{
			PII t=heap.top();
			if(t.x>=a[i].l) newInsert(i,cnt);	//情况1
			else
			{									//情况2
				heap.pop();						//更新堆顶的元素
				heap.push({a[i].r,a[i].id});
				ans[a[i].id]=ans[t.y];			//第i个区间的棚号为原堆顶元素的棚号
			}
		}
	}
	cout<<cnt<<endl;
	for(int i=1;i<=n;i++) cout<<ans[i]<<endl;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lwz_159

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值