POJ 3485 Highway(貪心演算法)

來源:互聯網
上載者:User

    這個題目是比較經典的貪心演算法,可以對這個題目轉換一下,所有的點到公路的距離在要求的範圍之內會形成一個個線段,也就是說現在要求出最少的點

使這些點能覆蓋所有區間,也就是每個區間都有點,這樣只要按照區間的右端點排序,每次點就放在右端點就OK了,然後向後尋找左端點在剛才的點的右邊

的接著放,一直到所有村莊的線段都處理完成,這個貪心演算法也算是完成了!

#include <iostream>#include <string.h>#include <stdio.h>#include <cmath>#include <algorithm>using namespace std;struct point{    double left;    double right;}po[100000];int cmp(const void *a,const void *b){    return (*(point*)a).right < (*(point*)b).right ? -1 : 1;}int main(){    double way_long,dis;    int n,i,j,k;    double a,b;    double rec;    int re;    while(scanf("%lf%lf%d",&way_long,&dis,&n)!=EOF)    {        re=0;        for(i=0;i<n;i++)        {        scanf("%lf%lf",&a,&b);        rec=sqrt(dis*dis-b*b);        po[i].left=a-rec;        po[i].right=a+rec;        if(po[i].left < 0)        po[i].left=0;        }        qsort(po,n,sizeof(po[0]),cmp);       // for(i=0;i<n;i++)        //printf("%lf\n",po[i].right);        re=0;        i=0;        while(i<n)        {            k=i;            re++;            while(i<n && po[i].left <= po[k].right) i++;        }        printf("%d\n",re);    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.