(3)A - 贪心

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
Hint
Explanation of the sample:

Here's a graphical schedule for this output:

Time     1  2  3  4  5  6  7  8  9 10

Stall 1 c1>>>>>>>>>>>>>>>>>>>>>>>>>>>
Stall 2 .. c2>>>>>> c4>>>>>>>>> .. ..
Stall 3 .. .. c3>>>>>>>>> .. .. .. ..
Stall 4 .. .. .. c5>>>>>>>>> .. .. ..
Other outputs using the same number of stalls are possible.
题意:给出每个奶牛的挤奶时间,一台机器只能挤一头奶牛,至少要多少太机器,输出奶牛使用机器的编号。思路:按照每一头奶牛的开始时间,用优先队列,将奶牛入队,如果前者开始时间大于后者,则需要添加机器。注释理解

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
int flag[50005];
struct node
{
 int cow;
 int tim;
 int num;//记录第几个奶牛
 friend bool operator <(node a,node b)
 {
  if(a.tim==b.tim)//时间相同时,结束时间从小到大排,保证优先只用一个机器
  {
   return a.cow<b.cow;
  }
  return a.tim>b.tim;
 }
}m[50005];
bool cmp(node x,node y)//排序
{
 if(x.cow!=y.cow)
 return x.cow<y.cow;
 else
 return x.tim<y.tim;
}
priority_queue<node>temp;
int main()
{
 int n,i,sum;
 while(cin>>n)
 {
  for(i=0;i<n;i++)
  {
   cin>>m[i].cow>>m[i].tim;
   m[i].num=i;
  }
  
  sort(m,m+n,cmp);
  sum=1;
  temp.push(m[0]);
  flag[m[0].num]=1;
  for(i=1;i<n;i++)
  {
   if(!temp.empty()&&temp.top().tim<m[i].cow)
   {
    flag[m[i].num]=flag[temp.top().num];
    temp.pop();
   }
   else
   {
    sum+=1;//第几个机器
    flag[m[i].num]=sum;
   }
   temp.push(m[i]);
  }
  cout<<sum<<endl;
  for(i=0;i<n;i++)
  {
   cout<<flag[i]<<endl; 
  }
  while(!temp.empty())
  {
   temp.pop();
  }
 }
 return 0;
}

猜你喜欢

转载自blog.csdn.net/whhhzs/article/details/79385210