[C++]Radar Installation--POJ1328

[C++]Radar Installation POJ - 1328

Radar Installation:
將一條海岸線看成X軸,X軸上面是大海,海上有若干島嶼,給出雷達的覆蓋半徑和島嶼的位置,要求在海岸線上建雷達,在雷達能夠覆蓋全部島嶼情況下,求雷達的最少使用量。

輸入格式:
n (1<=n<=1000) and d
This is followed by n lines each containing two integers representing the coordinate of the position of each island. Then a blank line follows to separate the cases.
The input is terminated by a line containing pair of zeros
輸出格式:
For each test case output one line consisting of the test case number followed by the minimal number of radar installations needed. “-1” installation means no solution for that case.

輸入:
3 2
1 2
-3 1
2 1

1 2
0 2

0 0
輸出:
Case 1: 2
Case 2: 1

解題分析:
每個島嶼在海岸線能被探測到的位置都有一個區間,把能探測到島嶼的每個區間求出來,此時就變成了區間問題,問有多少個獨立的區間塊。

AC代碼:

#include<iostream>
#include<cmath>
#include<algorithm>
#include<utility>
#include<vector>
using namespace std;

typedef pair<double, double> P;
double n, d;
struct ST{
	double left;
	double right;
};

int cmp(P a, P b){
	return a.first < b.first;
}

int main(){
	int Case = 1;
	while(cin>>n>>d){
		if(n == 0 && d == 0)
			break;
		ST st[1010];
		vector<P> vec;
		int flag = 0;
		for(int i = 0; i<n; i++){
			cin>>st[i].left>>st[i].right;
			if(fabs(st[i].right) > d)
				flag = 1;
			double left = st[i].left*1.0 - sqrt(d*d - st[i].right*st[i].right);
			double right = st[i].left*1.0 + sqrt(d*d - st[i].right*st[i].right);
//			 cout<<left<<" "<<right<<endl;
			vec.push_back(P(left, right));
		}
		if(flag){
			cout<<"Case "<<Case++<<": "<<-1<<endl;
			continue;
		}
		sort(vec.begin(), vec.end(), cmp);
		int res = 1;
		double end = vec[0].second;
		for(int i = 1; i<vec.size(); i++){
			if(vec[i].second < end){
				end = vec[i].second;
			}
			else if(vec[i].first > end){
				end = vec[i].second;
				res++;
			}
		}
		
		cout<<"Case "<<Case++<<": "<<res<<endl;
	}
	
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章