题目:http://poj.org/problem?id=1328
AC代码(C++):
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string.h>
using namespace std;
struct PAIR{
double left;
double right;
bool vis;
};
bool cmp(PAIR a, PAIR b){
return a.right<b.right;
}
int main(){
int n,d;
int Case = 0;
while(cin>>n>>d){
if(n==0)break;
Case++;
vector<PAIR> pairs;
bool flag = false;
for(int i = 0; i < n; i++){
int x,y;
cin>>x>>y;
if(y>d||d<0)flag = true;
PAIR tmp;
tmp.left = (double)x - sqrt((double)d*d-(double)y*y);
tmp.right = (double)x + sqrt((double)d*d-(double)y*y);
tmp.vis = false;
pairs.push_back(tmp);
}
getchar();
getchar();
sort(pairs.begin(),pairs.end(),cmp);
int m = 0;
for(vector<PAIR>::iterator it = pairs.begin(); it != pairs.end(); it++){
if(it->vis==false){
it->vis = true;
for(vector<PAIR>::iterator itt = pairs.begin(); itt != pairs.end(); itt++){
if(itt->left<=it->right&&itt->vis==false){
itt->vis = true;
}
}
m++;
}
}
if(flag==false)cout<<"Case "<<Case<<": "<<m<<endl;
else cout<<"Case "<<Case<<": -1"<<endl;
}
}
总结:
刚看完题感觉没思路, 看过别人的解题思路后才知道用贪心算法. 做每个点为圆心的半径为d的圆, 记录交于x轴的左右两点. 设有AB两岛, 若B岛的左点在A岛的左右两点间, 则AB两岛共一个雷达站.