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:
Input
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
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
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.
Sample Input
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 7Sample Output
4 1 2 3 2 4Hint
Explanation of the sample:
Here's a graphical schedule for this output:
Here's a graphical schedule for this output:
Time 1 2 3 4 5 6 7 8 9 10Other outputs using the same number of stalls are possible.
Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>>
Stall 2 .. c2>>>>>> c4>>>>>>>>> .. ..
Stall 3 .. .. c3>>>>>>>>> .. .. .. ..
Stall 4 .. .. .. c5>>>>>>>>> .. .. ..
代码:
#include <iostream> #include <algorithm> #include <queue> #include <cstdio> using namespace std; class time { public: int a,b; int id; friend bool operator <(time x,time y) { if(x.b==y.b)return x.a>y.a;///右端点相同 则取左端点靠前的 即最先被分配的 return x.b>y.b;///堆顶元素,右端点最小 } }s[50001]; int cmp(time x,time y) { if(x.a==y.a)return x.b < y.b;///左端点相同的 右端点也升序 return x.a < y.a;///左端点升序排序 } int main() { int n,used[50001],ans = 0; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d%d",&s[i].a,&s[i].b); s[i].id=i; } sort(s,s+n,cmp); priority_queue<time> q; for(int i = 0;i < n;i ++) { if(!q.empty()&&s[i].a > q.top().b)///和队顶比较 队顶保存的是最靠前的,如果满足条件可以插在它的后面,公用一个stall { used[s[i].id]=used[q.top().id]; q.pop(); } else///否则另加一个stall { ans++; used[s[i].id]=ans; } q.push(s[i]); } cout<<ans<<endl; for(int i=0;i<n;i++) cout<<used[i]<<endl; }