Stall Reservations(贪心算法)

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

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
struct Cow{
    int a,b;
    int no;
    bool operator <(const Cow &c) const{
        return a<c.a;//根据牛挤奶的开始时间从小到大排序
    }
}cows[50001];
   int pos[50001];
struct stoll{
    int ed;
    int no;
    bool operator <(const stoll &s) const{
        return ed>s.ed;//在优先队列中,此表示最小的在队列前面
    }
};
priority_queue <stoll> q;
int main(){
   int n;
   int num=0;
   scanf("%d",&n);
   for(int i=0;i<n;i++){
    scanf("%d%d",&cows[i].a,&cows[i].b);
    cows[i].no=i;
   }
   sort(cows,cows+n);
   int cnt=0;
   for(int i=0;i<n;i++){
    if(q.empty()){//若队列为空,则直接分配栅栏
        cnt++;
        stoll s;
        s.ed=cows[i].b;
        s.no=cnt;

        q.push(s);
        pos[cows[i].no]=cnt;
    }
    else{
        stoll st=q.top();
        if(st.ed<cows[i].a){//若此刻的奶牛挤奶的开始时间大于队列中结束时间最短的(说明直接可以进入该栅栏,无需分配其他)
            q.pop();//删除上头牛的记录
            stoll s;
            s.ed=cows[i].b;
            s.no=st.no;
            q.push(s);//把此刻占用栅栏的牛的信息放入队列
            pos[cows[i].no]=s.no;
        }
        else{
            cnt++;
            stoll s;
            s.ed=cows[i].b;
            s.no=cnt;
            q.push(s);
            pos[cows[i].no]=cnt;
        }
    }
   }
   printf("%d\n",cnt);
   for(int i=0;i<n;i++){
    printf("%d\n",pos[i]);
   }
}

猜你喜欢

转载自blog.csdn.net/lijunyan5/article/details/81505198