poj3190 Stall Reservations

本文介绍了一个使用贪心算法解决牛棚分配问题的方法。通过使用priority_queue来维护所有牛棚中结束时间最早的牛棚,实现了有效的资源分配。文章提供了一段详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我一开始想用线段树,但是发现还要记录每头cow所在的棚......

无奈之下选择正解:贪心。

用priority_queue来维护所有牛棚中结束时间最早的那个牛棚,即可得出答案。

注意代码实现的细节。

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <queue>
 4 using namespace std;
 5 const int N = 50010;
 6 struct Cow {
 7     int a, b, num;
 8     bool operator < (const Cow& x) const {
 9         return this->a < x.a;
10     }
11     bool operator > (const Cow& x) const {
12         return this->a > x.a;
13     }
14 }c[N];
15 priority_queue< Cow, vector<Cow>, greater<Cow> >Q;
16 int ans[N];
17 int main() {
18     int n, top = 0;
19     scanf("%d", &n);
20     for(int i = 1; i <= n; i++) {
21         scanf("%d%d", &c[i].a, &c[i].b);
22         c[i].num = i;
23     }
24     sort(c + 1, c + n + 1);
25     Cow x;
26     x.a = c[1].b;
27     x.b = ++top;
28     ans[c[1].num] = top;
29     Q.push(x);
30     for(int i = 2; i <= n; i++) {
31         //printf("i:%d c[i].b:%d Q.top().a:%d\n", c[i].num, c[i].b, Q.top().a);
32         if(Q.top().a < c[i].a) {
33             x = Q.top();
34             Q.pop();
35             x.a = c[i].b;
36             ans[c[i].num] = x.b;
37             Q.push(x);
38         }
39         else {
40             x.a = c[i].b;
41             x.b = ++top;
42             ans[c[i].num] = top;
43             Q.push(x);
44         }
45     }
46     printf("%d\n", top);
47     for(int i = 1; i <= n; i++) {
48         printf("%d\n", ans[i]);
49     }
50     return 0;
51 }
AC代码

 

转载于:https://www.cnblogs.com/huyufeifei/p/9013734.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值