刚开学的时候,课程设计的时候写过这道题,当时用c写的,排序用的选择排序,现在用c++写了下,用的快排,哇,惊人的发现在oj上后者比前者慢一倍,c的输入输出这么快的吗?
本题贪心算法里面的区间问题。思路:
计算小岛的雷达安装范围,对全部的安装范围按照左端点进行排序,然后从左到右,如果两个区间有交叉,不用安装;如果包含,更新右端点;如果没有交点,安装雷达,更新右端点。
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
struct point
{
double left, right;
};
point a[1005];
bool cmp(point a, point b)
{
return a.left < b.left;
}
int main()
{
int n, r;
int num = 0;//输入数据次数
int count;//雷达数量
int x, y;//接受横纵坐标
while (cin >> n >> r, n || r)
{
num++;
bool flag = true;
for (int i = 0; i < n; i++)
{
cin >> x >> y;
if (y > r)flag = false;
else
{
double d = sqrt(r*r - y*y);
a[i].left = x*1.0 - d;
a[i].right = x*1.0 + d;
}
}
if (!flag)
cout << "Case " << num << ": -1" << endl;
else
{
sort(a, a + n,cmp);
double s = a[0].right; count = 1;
for (int i = 1; i < n; i++)
{
if (a[i].left > s) //没有交点的时候,安装雷达
{
count++;
s = a[i].right;
}
else if (a[i].right < s) //前者包含后者的时候,更新右端点;
s = a[i].right;
//交叉什么也不用做
}
cout << "Case " << num << ": ";
cout << count << endl;
}
}
system("pause");
}