题目描述:
分析:
这道题其实跟喷水装置的思路是一样的,不过这里需要把数据转换一下,根据以给点的坐标和半径算出该装置可以覆盖的区间。这样就把问题转化成了找出最小的区间数去完全覆盖一个给定的区间。这里做了一点优化。如果该装置连高都不能覆盖,肯定不进行考虑。
将所有可以覆盖到高的装置加入数组中,用j来记录实际有多少个可用装置。然后对可用的装置进行排序,按照区间的起始点升序排列,如果起始点相同,按终点降序排列。
如果起始点最小的区间不能覆盖到0,那肯定没有方案可以覆盖整个草坪。依次扫描排序之后的数组,每次都找出起点比当前重点小的,终点最大的区间。
参考代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct tu
{
double s;//开始坐标
double e;//结束坐标
};
int compare(const void * a, const void * b);
int main()
{
struct tu a[600];
int n,w,h;
int x,r;
double l,Max;
int i,t,j;
int sum;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d",&n, &w, &h);
for(i = 0, j = 0; i < n; ++i)
{
scanf("%d %d",&x, &r);
l = (double)(r * r - h * h / 4);
if(l <= 0)//判断这个装置是否可以覆盖高
continue;
a[j].s = x - sqrt(l);
a[j].s = a[j].s > 0 ? a[j].s : 0;
a[j].e = x + sqrt(l);
a[j].e = a[j].e < w ? a[j].e : w;
++j;
}
if(j < 1)//如果没有装置能够覆盖到h
{
printf("0\n");
continue;
}
qsort(a,j,sizeof(a[0]),compare);
l = a[0].s;
if(l > 0)//如果不能覆盖0
{
printf("0\n");
continue;
}
i = 0;
l = a[0].e;
sum = 1;
while(l < w && i < j)
{
++sum;
Max = 0;
while(a[i].s < l && i < j)
{
//找起始点比当前小,终点最远的一个区间
Max = Max > a[i].e - l ? Max : a[i].e - l;
++i;
}
l += Max;
if(i >= j)
{
break;
}
//找到下一个能和这个区间连接的区间
}
if(l >= w)
printf("%d\n", sum);
else
printf("0\n");
}
}
int compare(const void *a, const void *b)
{
//按起始坐标升序排列,如果起始坐标相同,按终点坐标降序排列
struct tu *p1 = (struct tu *)a;
struct tu *p2 = (struct tu *)b;
if(p1->s - p2->s > 0.00001)
return 1;
else if(p1->s - p2->s < -0.00001)
return -1;
else
{
if(p2->e - p1->e > 0.00001)
return 1;
else if(p2->e - p1->e < -0.00001)
return -1;
else
return 0;
}
}