B

来源:互联网 发布:3dmax软件打不开 编辑:程序博客网 时间:2024/04/30 08:28
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
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 stalls are possible.




解题思路:

先用sort()函数将开始时间进行排序

其次就是利用优先队列将 结尾时间进行排序

因为顺序是时间小的在前面 所以不用担心 后面的开始时间都比前面的开始时间大

然后比较开始时间与队首的结尾时间

如果 可以在同一个棚里面 那么就把先前的那个剔除出去

如果不行的话 那么棚数++

一句话  我也是抄网上的代码的


C++代码:

#include <iostream>  
#include <algorithm>  
#include <cstdio>  
#include <cstring>  
#include <queue>  
using namespace std;  
  
struct node  
{  
    int x;
int y;
int num;  
}no[50005];  
int used[50005];  //用来存放每只奶牛在那个棚的 
  
bool operator<(node a,node b)  
{  
    return a.y>b.y;     //从小到大排序   表示从小到大排列  这一步问题有点大  
}  
  
bool cmp(node a,node b)  
{  
    return a.x<b.x;   // sort()函数排序 利用的是开始的时间的比较  
}  
  
int n;   
int main()  
{  
   int i;
   scanf("%d",&n);
   for(i=0;i<n;i++)
   {
    scanf("%d%d",&no[i].x,&no[i].y);
    no[i].num=i+1;  //比如说no[0]=1; 主要是为了表示第一只牛 这是一定的no[1]=2; 
   } //输入完成了 那么需要排序了
   sort(no,no+n,cmp);//将开始的时间从小到大排序;
   //弄一个优先队列
   priority_queue<node>q;
   used[no[0].num]=1;//表示第一只牛   在第一个仓棚里面;  
   q.push(no[0]);
   int ans=1;
   node a; 
   for(i=1;i<n;i++)
   {
    a = q.top();//每个都是起始的元素;
if(no[i].x>a.y) 
    {
    //因为刚开始的时间都比结束的大了 所以直接剔除出去 因为接下来开始时间也比开始的时间大
q.pop();
q.push(no[i]);
used[no[i].num]=used[a.num]; 
    }
    else
{
      ans++;
      q.push(no[i]);
      used[no[i].num]=ans;
    }
   } 
   
   printf("%d\n",ans);
   for(i=1;i<=n;i++)
   printf("%d\n",used[i]);
   return 0; 
}