POJ 3485 Highway (贪心, 区间选点)

Description

Bob is a skilled engineer. He must design a highway that crosses a region with few villages. Since this region is quite unpopulated, he wants to minimize the number of exits from the highway. He models the highway as a line segment S(starting from zero), the villages as points on a plane, and the exits as points on S. Considering that the highway and the villages position are known, Bob must find the minimum number of exists such that each village location is at most at the distance D from at least one exit. He knows that all village locations are at most at the distance D from S.

Input

The program input is from a text file. Each data set in the file stands for a particular set of a highway and the positions of the villages. The data set starts with the length L (fits an integer) of the highway. Follows the distance D (fits an integer), the number N of villages, and for each village the location (x,y). The program prints the minimum number of exits.

White spaces can occur freely in the input. The input data are correct and terminate with an end of file.

Output

For each set of data the program prints the result to the standard output from the beginning of a line. An input/output sample is in the table below. There is a single data set. The highway length L is 100, the distance D is 50. There are 3villages having the locations (2, 4)(50, 10)(70, 30). The result for the data set is the minimum number of exits: 1.

Sample Input

100
50
3
2 4
50 10
70 30

Sample Output

1

X轴上公路从0到L,X轴上下有一些点给出坐标代表村庄,问在公路上最少建几个出口才能使每个村庄到出口的距离不超过D。

以每个村庄坐标为圆心,D为半径画圆,与X轴有两个交点,那么N个村庄就会得到N个区间,这就转化为了区间选点问题。策略为:先按区间的左端点从小到大,右端点从小到大排序,每次都以一个村庄的右端点为基准。这与http://blog.csdn.net/misdom_tian_ya/article/details/44310197思路是类似的。

#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <math.h>
using namespace std;
struct Node
{
    double left,right;
};
bool cmp(Node A,Node B)
{
    if(A.left!=B.left)
        return A.left<B.left;
    else
        return A.right<B.right;
}
int main()
{
    int L,D,N;
    double x,y;
    while(cin>>L)
    {
        cin>>D>>N;
        Node node[10000];
        for(int i=0;i<N;i++)
        {
            cin>>x>>y;
            node[i].left=x-sqrt(D*D-y*y);
            node[i].right=x+sqrt(D*D-y*y);
        }
        sort(node,node+N,cmp);
        double temp=node[0].right;
        int sum=1;
        for(int i=1;i<N;i++)
        {
            if(temp>L)
                temp=L;
            if(node[i].left>temp)
            {
                sum++;
                temp=node[i].right;
            }
            else
                temp=node[i].right<temp?node[i].right:temp;
        }
        cout<<sum<<endl;
    }
    return 0;
}

你可能感兴趣的:(POJ 3485 Highway (贪心, 区间选点))