1.Question:
题意:
题目中抽象了一个俯视图,以x轴为海岸线,y的负半轴一下是陆地,y的正半轴是海洋,在海洋上有很多岛屿
我们有一中雷达,雷达的侦测半径是d,现在要我们输出可以将所有的岛屿全部都侦测到的最少的雷达的个数
我们定义输入:
n,d分别代表岛屿的个数和我们的雷达的半径
之后的n行两个数据代表了岛屿的坐标(小心坐标的值可以使负数,也可以d大)
本题有多组输入,当遇到输入n,d都是0的时候终止输出并返回
2.Solution:
本题是 区间选点问题 的一种很典型的变体
我们解决区间选点问题标准是贪心的思路
贪心的描述如下:
以所有的区间的右端点升序排列,右端相同按左端的降序排列
我们从头开始,一旦遇到下一个区间的左端比上一个选定的区间的右端大,说明我们至少需要再增加一个雷达来满足所有的区间覆盖,然后我们将选定的区间在移动至当前的区间
证明很麻烦(好吧我不会):我还是太渣了
为了弥补过失我将 <algorithm>下的qsort和sort函数大致的讲解一下
这两个函数一直是算法考试的常考点,并且两者还有一些区别(总的来说sort比qsort更优秀一些)
qsort(数组的首地址,数组待排的长度,数组中的单元的字节大小,cmp)cmp比较函数
比较函数算是最难的一点:
cmp只能返回int类型,所以说对于其他数据类型进行排序的时候,我们一般都用三元运算符表达层次关系
int cmp(const void* a,const void* b) //注意这里是void类型的含义是我们之后要对void类型进行强制转换,转换成对应的类型进行比较
{
return *(type*)a > *(type*)b ? 1:-1;
}
我们需要注意,在qsort的cmp中,返回正数表示a,b要交换位置,0表示无所谓交不交换,负数代表a,b不交换位置
bool cmp(type a,type b,cmp)
{
return true; //返回true代表不用交换为止
return false; //返回false代表需要交换位置
}
本题的话,利用sort或者qsort都可以实现
3.Code:
#include"iostream"
#include"cstdlib"
#include"cstdio"
#include"cstring"
#include"algorithm"
#include"cmath"
#define N 1005
using namespace std;
typedef struct node
{
double x;
double y;
}point;
point line[N];
int n,d;
int coun;
int sum=0;
bool cmp(point a,point b)
{
if(a.y<b.y) return true;
else if(a.y==b.y)
{
if(a.x>b.x) return true;
else return false;
}
else return false;
}
int main()
{
int t=1;
while(scanf("%d%d",&n,&d)&&(n||d))
{
sum=0;
int x;
int y;
coun=0;
bool ok=true;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);
if(d*d-y*y*1.0<0||d<0) ok=0;
else
{
line[coun+1].x=x*1.0-sqrt(d*d*1.0-y*y*1.0);
line[++coun].y=x*1.0+sqrt(d*d*1.0-y*y*1.0);
}
}
if(ok==false)
{
printf("Case %d: -1\n",t++);
continue;
}
sort(line+1,line+1+coun,cmp);
sum=1;
point temp=line[1];
for(int i=2;i<=coun;i++)
{
if(line[i].x>temp.y) sum++,temp=line[i];
}
printf("Case %d: %d\n",t++,sum);
}
return 0;
}
NYOJ 891
同一个思路,不说什么了
Code:
#include"iostream"
#include"cstdio"
#include"cstdlib"
#include"cstring"
#include"algorithm"
using namespace std;
typedef struct node
{
int x;
int y;
}point;
int n;
point line[105];
bool cmp(point a,point b)
{
if(a.y<b.y) return true;
else if(a.y==b.y)
{
if(a.x>b.x) return true;
else return false;
}
else return false;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int x,y;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);
line[i].x=x;
line[i].y=y;
}
sort(line+1,line+1+n,cmp);
int sum=1;
point temp=line[1];
for(int i=2;i<=n;i++)
{
if(line[i].x>temp.y) sum++,temp=line[i];
}
printf("%d\n",sum);
}
return 0;
}