挑战程序设计竞赛 2.2章习题 poj 3190 Stall Reservations(贪心+优先队列)

地址 https://vjudge.net/problem/POJ-3190

题目大意
一群母牛安排挤奶,挤奶需要占用一间牛棚。每头牛不能和其他母牛共用牛棚。
根据每头牛的挤奶时间安排牛棚,询问最少需要多少牛棚,并且给出每头牛挤奶使用的牛棚号。

输入
第一行一个数字N 表示有N头牛
下面N行为每头牛挤奶的起始时间 每行两个数字 空格间隔

输出
第一行输出最少需要多少牛栏
下面N行输出每头牛挤奶占用的牛棚编号

样例
Sample Input
5
1 10
2 4
3 6
5 8
4 7
Sample Output
4
1
2
3
2
4

解答
接收每头牛的挤奶起始时间,然后按照起始时间排序,这样就可以按照奶牛开始挤奶的时间进行牛棚的安排,如果有空的牛棚则直接使用,如果当前轮到某头牛挤奶,但是没有牛棚,则新添一间牛棚。
但是如何得到当前时间是否有空的牛棚。这里使用优先队列来存储牛棚,以占用牛棚的牛的挤奶结束时间进行排序,得到当前结束时间最早的牛棚。

题外话 考虑过使用哈希记录每头牛对应的牛棚号,但是poj不支持unordered_map
代码

// poj 3190.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <queue>
#include <vector>
//#include <unordered_map>
#include <algorithm>

using namespace std;


/*
Input
Line 1: A single integer, N
Lines 2..N+1: Line i+1 describes cow i's milking interval with two space-separated integers.
Output
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.
Sample Input

5
1 10
2 4
3 6
5 8
4 7
Sample Output

4
1
2
3
2
4
*/


struct COW {
	int start;
	int end;
	int num;
	int stall;
};


struct cmp {
	bool operator()(struct COW& x, struct COW& y)
	{
		return  x.end > y.end;
	}
};

priority_queue<struct COW, vector<struct COW>, cmp> q;    //定义方法
int n;
 

bool cmp_COW(const struct COW& a, const struct COW& b) {
	return a.start < b.start;
}

struct COW mm[1000010];

int main()
{
	cin >> n;
	vector<struct COW> arr;
	for (int i = 0; i < n; i++) {
		int a, b;
		cin >> a >> b;

		struct COW t; t.start = a; t.end = b; t.num = i;
		arr.push_back(t);
	}

	sort(arr.begin(), arr.end(),cmp_COW);

	int ans = 0;
	//unordered_map<int, struct COW> mm;

	for (int i = 0; i < arr.size(); i++) {
		if (q.empty() || q.top().end >= arr[i].start) {
			ans++;
			arr[i].stall = ans;
			q.push(arr[i]);
		}
		else {
			struct COW t = q.top();
			mm[t.num] = t;
			q.pop();
			arr[i].stall = t.stall;
			q.push(arr[i]);
		}
	}
	
	cout << ans << endl;

	while (!q.empty()) {
		struct COW t = q.top();
		mm[t.num] = t;
		q.pop();
	}

	for (int i = 0; i < n; i++) {
		cout << mm[i].stall << endl;
	}
	
	return 0;
}

posted on   itdef  阅读(48)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
历史上的今天:
2019-08-04 AcWing 30. 正则表达式匹配 (剑指OFFER leetcode 10)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示