您的位置:首页 > 编程语言 > C语言/C++

POJ-3190-Stall Reservations-优先队列+贪心

2017-11-21 19:45 441 查看
题目来源:http://poj.org/problem?id=3190

题目内容:Stall Reservations

Time Limit: 1000MS Memory Limit: 65536K

Total Submissions: 8013 Accepted: 2811 Special Judge

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

Hint

Explanation of the sample:

Here’s a graphical schedule for this output:

Time 1 2 3 4 5 6 7 8 9 10

Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>>

Stall 2 .. c2>>>>>> c4>>>>>>>>> .. ..

Stall 3 .. .. c3>>>>>>>>> .. .. .. ..

Stall 4 .. .. .. c5>>>>>>>>> .. .. ..

Other outputs using the same number of stalls are possible.

Source

USACO 2006 February Silver

题目分析:

将n头奶牛放入牛棚中产奶,奶牛信息包括产奶的起始时间start和终止时间end,只要到了开始产奶的时间奶牛就必须要开始产奶,每头奶牛在产奶期间要占用一整个牛棚,问n头奶牛产完奶至少需要多少个牛棚。以及输出每头奶牛最终所在的牛棚编号。

思路:

奶牛需要按照起始产奶时间进行排序,以便于确定当前的时间状态下该奶牛是否应该要产奶了。而牛棚则需要按照终止时间来排序,通过当前奶牛的起始时间和终止时间最近的牛棚的终止时间相比较,来确定是在当前牛棚加一头奶牛还是要新建一个牛棚。要注意的一个地方是在输出的时候他是按照输入的编号进行输出的,所以在输入的时候我们还要保留奶牛一开始的编号,以至于不会在排序的时候造成编号混乱的情况。主要代码如下:

struct Cow{
int start;
int end;
int no;
bool operator <(const Cow &c)const{
return start < c.start;
}
}cows[10005];
struct Stall{
int end;
int no;
bool operator <(const Stall &s)const{
return s.end < end;
}
}
int pos[10005];
int main(){
int n;
cin >> n;
for(int i = 0 ; i < n ; i ++){
cin >>  cows[i].start >> cows[i].end;
cows[i].no = i;
}

int cnt = 0;
priority_queue<Stall>pQ;
for(int i = 0 ; i < n ; i ++){
if(Q.empty()){
cnt ++;
Q.push(cows[i].end,cnt);
pos[cows[i].no] = cnt;
}else{
Stall stall = Q.top();
if(cows[i].start > stall.end){
Q.pop();
Q.push(cows[i].end,stall.no);
pos[cows[i].no] = stall.no;
}else{
cnt ++;
Q.push(cows[i].end,cnt);
pos[cows[i].no] = cnt;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息