1651: [Usaco2006 Feb]Stall Reservations 专用牛棚
Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 951 Solved: 550
[ Submit][ Status][ Discuss]
Description
有N头牛,每头牛有个喝水时间,这段时间它将专用一个Stall 现在给出每头牛的喝水时间段,问至少要多少个Stall才能满足它们的要求
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
经典题了
把线段转化成一个入点和一个出点,这样存下2*n个点,之后按坐标从小到大给这2*n个点排序,之后O(n)遍历一遍就好,遇到入点sum++, 遇到出点sum--,遍历时最大的sum便是答案,算上排序复杂度稳定nlogn(注意:排序时坐标相同的点出点优先,出点不在区间内)
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef struct
{
int x;
int flag;
}Point;
Point s[100005];
bool comp(Point a, Point b)
{
if(a.x<b.x || a.x==b.x && a.flag<b.flag)
return 1;
return 0;
}
int main(void)
{
int n, i, a, b, sum, ans;
scanf("%d", &n);
for(i=1;i<=n;i++)
{
scanf("%d%d", &a, &b);
s[i*2-1].x = a, s[i*2-1].flag = 1;
s[i*2].x = b+1, s[i*2].flag = -1;
}
n *= 2;
sort(s+1, s+n+1, comp);
sum = ans = 0;
for(i=1;i<=n;i++)
{
sum += s[i].flag;
ans = max(ans, sum);
}
printf("%d\n", ans);
return 0;
}