您的位置:首页 > 其它

NYOJ - 喷水装置(二)

2016-05-03 17:07 281 查看
描述 有一块草坪,横向长w,纵向长为h,在它的橫向中心线上不同位置处装有n(n<=10000)个点状的喷水装置,每个喷水装置i喷水的效果是让以它为中心半径为Ri的圆都被润湿。请在给出的喷水装置中选择尽量少的喷水装置,把整个草坪全部润湿。
输入第一行输入一个正整数N表示共有n次测试数据。

每一组测试数据的第一行有三个整数n,w,h,n表示共有n个喷水装置,w表示草坪的横向长度,h表示草坪的纵向长度。

随后的n行,都有两个整数xi和ri,xi表示第i个喷水装置的的横坐标(最左边为0),ri表示该喷水装置能覆盖的圆的半径。输出每组测试数据输出一个正整数,表示共需要多少个喷水装置,每个输出单独占一行。

如果不存在一种能够把整个草坪湿润的方案,请输出0。样例输入
2
2 8 6
1 1
4 5
2 10 6
4 5
6 5

样例输出
1
2


咋一看好像挺麻烦的,其实就是一个贪心算法和线段覆盖的题目。

下面贴代码,内有注释。

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

struct point
{
double left, right;
}water[10005];

bool cmp(point a, point b)
{
return a.left < b.left;
}

int main()
{
int T;
int n, w, h;    ///数据个数,宽度,高
double h_2;
int counts;
scanf("%d", &T);

while (T--)
{
int flag = 1;
counts = 0;

scanf("%d%d%d", &n, &w, &h);
h_2 = h/2.000000;
for (int i = 0; i < n; ++i)
{
int temp_x, temp_r;
double temp_w;
scanf("%d%d", &temp_x, &temp_r);

temp_w = sqrt(temp_r*temp_r - h_2*h_2);    ///只看这个喷水装置能占上(下)的宽度
if (temp_w > 0)
{
water[i].left = temp_x - temp_w;   ///分别求出左右交点
water[i].right = temp_x + temp_w;
}
}
sort(water, water+n, cmp);  ///按照左交点从小到大排序
double Max = 0;
double sum = 0;
while (sum < w)     ///只要还没覆盖全就一直覆盖
{
Max = 0;
for (int i = 0; i < n && water[i].left <= sum; ++i)///w[i].left<=sum保证两个碰水装置可以相交,也就是说两点直接的能够完全覆盖
{
if (water[i].right - sum > Max)///找出既能保证完全覆盖又能保证这点能够达到的右交点最大,即需要的喷水装置最少
{
Max = water[i].right - sum;
}
}
if (Max == 0)   ///如果没有就直接退出
{
flag = 0;
break;
}
else
{
counts++;
sum += Max;
}
}
if (flag == 1)
printf("%d\n", counts);
else
printf("0\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: