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 .. B (1 <= A <= B <= 1,000,000), where des both times A and B. obviusly, 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 stils required in the barn so that each cow can have her private milking Period
- An assignment of cows to these stils over time
Specified 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 stallthe 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 51 102 43 65 84 7 Sample output 412324 Hint Explanation of the sample:
Here's a graphical schedule for this output:
Time 1 2 3 4 5 6 7 8 9 10Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>>Stall 2 .. c2>>>>>> c4>>>>>>>>> .. ..Stall 3 .. .. c3>>>>>>>>> .. .. .. ..Stall 4 .. .. .. c5>>>>>>>>> .. .. .. Other outputs using the same number of stils are possible.Source Usaco 2006 February silver |
Amount, greedy question =. =, Priority queue in STL
Greedy strategy: sorts the milking start time from big to small, so that the milking start time is not considered before;
Sort the elements in the queue by the milking end time from small to large, so that the first time can be determined without adding a slot =. =
# Include <iostream> # include <cstdio> # include <cstring> # include <algorithm> # include <limits. h ># include <queue> using namespace STD; const int maxn = 1000000 + 10; struct node {int St, Ed; int Pos; // The number of cows whose POS records are bool operator <(const node & A) const {If (ED =. ed) return st>. st; return ed>. ed ;}} A [maxn]; int used [maxn]; // used records the position where the cows are milking =. = Int CMP (node L1, node l2) {If (l1.st = l2.st) return l1.ed <l2.ed; return l1.st <l2.st;} int main () {int N; while (~ Scanf ("% d", & N) {priority_queue <node> q; For (INT I = 1; I <= N; I ++) {scanf ("% d", & A [I]. st, & A [I]. ed); A [I]. pos = I;} Sort (a + 1, A + n + 1, CMP); q. push (A [1]); int ans = 1; used [A [1]. pos] = 1; for (INT I = 2; I <= N; I ++) {If (! Q. empty () & Q. top (). ed <A [I]. st) // determine whether the condition is met {used [A [I]. pos] = used [q. top (). pos]; q. pop ();} else // The number of non-conforming slots plus one. At the same time, this cow should be added in the slot {ans ++; used [A [I]. pos] = ans;} Q. push (A [I]);} printf ("% d \ n", ANS); For (INT I = 1; I <= N; I ++) printf ("% d \ n", used [I]);} return 0 ;}