POJ3190:stall reservations,考点:贪心策略

原题:http://poj.org/problem?id=3190

描述

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.

中文简洁易懂型描述:

输入

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

解法

思路:贪心

 

 注意事项:要记录奶牛原来在数组中的编号,因为输出的时候要用。以及优先队列的排序是反过来的,要记住。

 

 代码如下:(不一定AC,因为我找不到POJ账号了)

 1 #include <iostream>
 2 #include <queue>
 3 #include <vector>
 4 #include <algorithm>
 5 using namespace std;
 6 const int MAXN = 50005;
 7 struct cow {
 8     int start;
 9     int end;
10     int index;//原来在数组中的坐标
11     cow(int s,int e,int ori):start(s),end(e),index(ori){}
12     bool operator <(const cow A) const {
13         return start < A.start;
14     }
15 };
16 struct stall {
17     int id;
18     int lastendtime = -1;
19     stall(int l,int i):id(i),lastendtime(l){}
20 };
21 class compare {
22 public:
23     bool operator()(const stall A, const stall B) {
24         return A.lastendtime > B.lastendtime;
25     }
26 };
27 int main() {
28     int N;
29     cin >> N;
30     vector<cow>cows;
31     priority_queue<stall,vector<stall>,compare>stalls;
32     int result[MAXN];
33     for (int i = 0; i < N; i++) {
34         int s, e;
35         cin >> s >> e;
36         cows.push_back(cow(s, e, i));
37     }
38     sort(cows.begin(), cows.end());
39     int stallnum = 1;
40     stall top=stall(cows[0].end,stallnum++);
41     result[cows[0].index] = top.id;
42     stalls.push(top);
43     for (int i = 1; i < N;i++) {
44         top = stalls.top();//最早结束的
45         if (top.lastendtime < cows[i].start) {
46             stalls.pop();
47             top.lastendtime = cows[i].end;
48             result[cows[i].index] = top.id;
49             stalls.push(top);
50         }
51         else {
52             stall temp = stall(cows[i].end, stallnum++);
53             result[cows[i].index] = temp.id;
54             stalls.push(temp);
55         }
56     }
57     cout << stalls.size() << endl;
58     for (int i = 0; i < N; i++)
59         cout << result[i] << endl;
60     return 0;
61 }

 

posted @ 2021-07-14 17:20  永远是个小孩子  阅读(49)  评论(0编辑  收藏  举报