POJ--3190 Stall Reservations(贪心+最小堆)
记录
23:15 2023-5-7
http://poj.org/problem?id=3190
reference:《挑战程序设计竞赛(第2版)》第二章练习题索引 p135
Description
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.
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
贪心,我一开始的思路是错误的。一开始想先将点从左到右排序起来,x越小,y越大这样子排序。但是是错误的,看了discuss中的思路
按开始时间排序,然后从最早开始的牛加入堆中,堆按结束时间维护。每次加入的时候和堆顶比较,如果可以共用,那么把这个节点的结束时间更新,然后这新加的头牛的房间号置为堆顶的这头一样的,然后维护这个节点。这样找下去。然后再按输入的时候的顺序再排序输出房间号就好了。
http://poj.org/showmessage?message_id=165146
然后就些出来了,注意的点:
- priority_queue<T, vector
, greater > 是最小堆,默认是less 最大堆 - POJ不支持C++11,所以定义还是麻烦些,我看有人贴出来的code不少都用了一些trick的代码,只能说emmm,为什么不支持捏?
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define MAX_N 50000
typedef long long ll;
typedef unsigned int uint;
const int INF = 0x3f3f3f3f;
int N;
typedef struct item {
int x;
int y;
int index;
bool operator < (const item &rhs) const{
return this->y > rhs.y;
}
} P;
P v[MAX_N + 1];
bool comp1(const P lhs, const P rhs) {
return (lhs.x < rhs.x) || (lhs.x == rhs.x && lhs.y < rhs.y) ;
}
bool comp2(const P lhs, const P rhs) {
return lhs.y > rhs.y;
}
// priority_queue<P, std::vector<P>, decltype(comp2)* > pq(comp2);
priority_queue<P, std::vector<P> > pq;
int check[MAX_N + 1];
int result = 0;
void solve() {
while (!pq.empty())
pq.pop();
result = 0;
sort(v, v + N, comp1);
fill(check, check + N, -1);
check[v[0].index] = result;
pq.push(v[0]);
result++;
for(int i = 1; i < N; i++) {
P temp = pq.top();
if(temp.y < v[i].x) {
check[v[i].index] = check[temp.index];
temp.y = v[i].y;
pq.pop();
pq.push(temp);
} else {
check[v[i].index] = result;
result++;
pq.push(v[i]);
}
}
printf("%d\n", result);
for(int i = 0; i < N; i++) {
printf("%d\n", check[i] + 1);
}
}
int main() {
while (~scanf("%d", &N)) {
for(int i = 0; i < N; i++) {
scanf("%d %d", &(v[i].x), &(v[i].y));
v[i].index = i;
}
solve();
}
return 0;
}