uva 1615 Highway 高速公路 (貪心算法)

Highway


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 the standard input. 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.
Note: 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 3 villages 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


題意大約是給你無限多個點,還有一個D的值,要我們求在x軸上有儘量少的點的個數,使得對於給定的每個點,都有一個選出的點離他的距離不超過D。
這題目剛開始看着挺唬人的,但是仔細思考了一下,畫了一個圖:每個點爲圓心,D爲半徑畫一個圓。與x相加的部分就是我們要求的點的集合了(也就是個區間),然後我們就發現了這道題目就轉換成了貪心的經典問題區間選點問題。

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
int n;
double r,L;
struct node                              //建立node來儲存點和區間。
{
    double x,y;
}v[100010],p[100010];                    //v來存點,p來存區間。
bool cmp(const node &a,const node &b)    //比較函數,以區間左端的排序。
{
    return a.x<b.x;
}
double ld(node z)                        //求歐幾里德距離的函數。
{
    return sqrt((r*r)-(z.y*z.y));
}

int main()
{
    while(cin>>L>>r>>n)
    {
        int sum=1;
        for(int i=0;i<n;i++)
        {
            cin>>v[i].x>>v[i].y;
            double ll=ld(v[i]);
            p[i].x=v[i].x-ll;
            p[i].y=v[i].x+ll;
        }
        sort(p,p+n,cmp);                 //因爲這裏的貪心策略是第一個區間要先取點。
        double ly=p[0].y;
        for(int i=1;i<n;i++)
        {
            if(p[i].x<=ly) ly=min(ly,p[i].y);
            else
            {
                ly=p[i].y;
                sum++;
            }
            if(ly>L) ly=L;               //題目的區間是有L限制的。
        }
        cout<<sum<<endl;

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章