这次我们尝试分解题目(毕竟我接触这些东西也才就几天),让我们慢慢来:
一、输入输出一组数据
以输入
3 2
1 2
-3 1
2 1
为例:
//安装雷达
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int n,d;
struct node{
int x,y;
}l[10000];
int main()
{
scanf("%d%d",&,&d);
for(int i=0;i<n;i++){
scanf("%d%d",&l[i].x,&l[i].y);
}
printf("%d %d\n",d,n);
for(int i=0;i<n;i++){
printf("%d %d\n",l[i].x,l[i].y);
}
return 0;
}
输入输出:
3 2
1 2
-3 1
2 1
2 3
1 2
-3 1
2 1
这里利用了之前的结构体构造数组,并不困难·,还有其它方法,不再赘述,重点不在这里
第一次尝试(失败)
不好意思了,时间有限,博主也很忙!上终代码:
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
struct LR
{
double l,r;
}lr[1010];
bool cmp(LR a,LR b)
{
if(a.r==b.r){
return a.l>b.l;
}
return a.r<b.r;
}
//3.创建比较函数,用布尔类型(True && False || 1 && 0)进行判断
int main()
{
int n,d,cases=0;
double x,y;
while(1){
//4.用 0 结束的常用操作
cin>>n>>d;
if(0){
break;
}
bool flag=d>=0;
//5.本质上说就是表示True!
for (int i=0;i<n;++i){
cin>>x>>y;
y<=d;
//6.反之该小岛不可能被雷达覆盖
if(flag){
lr[i].l=x-sqrt(d*d-y*y);
lr[i].r=x+sqrt(d*d-y*y);
}
}
//7.计算左右端点坐标
sort(lr,lr+n,cmp);
//8.使用 sort 函数(见下面讲解)
//8.实现了贪心算法的排序前提
int MIN=-1;
if(flag){
MIN=1;
double maxr=lr[0].r;
for (int i=1;i<n;++i){
if(lr[i].l>maxr){
maxr=lr[i].r;
MIN+=1;
}
//9.不断更新最右的与之前互不相容的小岛,直到找到最优解
}
}
cout<<"Case "<<++cases<<": "<<MIN<<endl;
//10.会用这种输出方式!简洁
}
return 0;
}
代码分析:
1.贪心算法的应用
2…创建结构体,用来存储以小岛为圆心,d 为半径画的圆与海岸线所相交的线段的左右坐标
(之后的放在代码注释中了)
补充:8.sort函数有三个参数:
(1)要排序数组的起始地址
(2)要排序数组的最后一个数据元素的下一个地址
(3)排序方法,如果没有排序方法的话,默认从小到大排序
输入输出:
3 2
1 2
-3 1
2 1
Case 1: 2
1 2
0 2
Case 2: 1
0 0
但是测评 output limit exceeded ,输出了一些别的东西,还是需要改进。。。
能力有限,参考了其他大佬的代码:
#include<iostream>
#include<math.h>
#include<algorithm>
using namespace std;
const int Max = 1005;
#include<stdio.h>
#include<string.h>
struct
{
int x, y;
}isl[Max];
struct data
{
float sta, end;
}rad[Max],temp;
bool cmp(data a, data b)
{
if(a.end < b.end)
return true;
else
return false;
}
int main()
{
int n, d, t = 1;
while(scanf("%d%d",&n,&d) && n != 0)
{
int i, j, max_y = 0;
for(i = 0; i < n; i ++)
{
cin >> isl[i].x >> isl[i].y;
if(isl[i].y > max_y)
max_y = isl[i].y;
}
getchar();
getchar();
cout << "Case " << t ++ << ": ";
if(max_y > d || d < 0)
{
cout << -1 << endl;
continue;
}
float len;
for(i = 0; i < n; i ++)
{
len = sqrt(1.0 * d * d - isl[i].y * isl[i].y);
rad[i].sta = isl[i].x - len;
rad[i].end = isl[i].x + len;
}
sort(rad, rad + n, cmp);
int ans = 1;
temp=rad[0];
for(i=1;i<n;i++)
{
if(rad[i].sta>temp.end)
{
ans++;
temp=rad[i];
}
else if(rad[i].end<temp.end)
temp=rad[i];
}
cout << ans << endl;
}
return 0;
}
分析:
To be continued…