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 }