POJ1328-Radar Installation
描述:
We use Cartesian coordinate system, defining the coasting is the x-axis. The sea side is above x-axis, and the land side below. Given the position of each island in the sea, and given the distance of the coverage of the radar installation, your task is to write a program to find the minimal number of radar installations to cover all the islands. Note that the position of an island is represented by its x-y coordinates.
Figure A Sample Input of Radar Installations
The input consists of several test cases. The first line of each case contains two integers n (1<=n<=1000) and d, where n is the number of islands in the sea and d is the distance of coverage of the radar installation. 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.
代码:
每一个海岛可以在产生一个圆心的范围,在该范围内的任意雷达都可以覆盖到该点。要求雷达的最少的数目,采用贪心的思路,就是使选择的圆心能够尽量的属于更多的圆心的区间。如果雷达范围无法到达某个点,则无解。
边输入边处理的时候,不能break。就因为这个RE了无数次(╯‵□′)╯︵┴─┴
#include <cmath> #include <cstdlib> #include <iostream> using namespace std; typedef struct{ double left; double right; }node; node a[1005]; int cmp(const void *a, const void *b){ return (*(node*)a).left >= (*(node*)b).left ? 1 : -1; } int main(){ int tc=1,n,d,flag,count,x,y; double delta,t; while( scanf("%d%d",&n,&d)!=EOF ){ if( n==0 && d==0 ) break; flag=1; if( d<=0 ) flag=0; for( int i=0;i<n;i++ ){ scanf("%d%d",&x,&y); if( y<=d ){//岛屿在雷达范围 delta=sqrt((double)(d*d-y*y)); a[i].left=x-delta;//得到区间 a[i].right=x+delta; } else{ flag=0;//这里不能写break,因为输入还未结束 } } if( flag==0 )//无解 printf("Case %d: -1\n",tc); else{ qsort(a,n,sizeof(node),cmp); t=a[0].right;count=1; for( int i=1;i<n;i++ ){ if( a[i].left>t ){//当前区间左界大于相交区间的最右 count++; t=a[i].right;//更新相交右界 } else{ if( a[i].right<t )//取相交的区间 t=a[i].right;//更新相交区间右界 } } printf("Case %d: %d\n",tc,count); } tc++; } system("pause"); return 0; }