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
Lines 2..N+1: Line i+1 describes cow i's milking interval with two space-separated integers.
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 7
4 1 2 3 2 4
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.
解题思路:
先用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;
}