poj 3258 River Hopscotch 【二分】

來源:互聯網
上載者:User

標籤:class   blog   code   tar   strong   2014   

題目真是不好讀,大意如下(知道題意就很好解了)

大致題意:

一條河長度為 L,河的起點(Start)和終點(End)分別有2塊石頭,S到E的距離就是L。

河中有n塊石頭,每塊石頭到S都有唯一的距離

問現在要移除m塊石頭(S和E除外),每次移除的是與當前最短距離相關聯的石頭,要求移除m塊石頭後,使得那時的最短距離儘可能大,輸出那個最短距離。

//Memory Time //420K   391MS #include<iostream>#include<algorithm>using namespace std;int main(void){int L;  //河總長int n;  //河中石頭數(除起點S和終點外E)int m;  //移除石頭數while(cin>>L>>n>>m){/*Input & Initial*/int* dist=new int[n+2];  //第i塊石頭到起點石頭的距離為dist[i]dist[0]=0;    //起點Sdist[n+1]=L;  //終點Eint low=L;   //上界(一次跳躍的最短距離)int high=L;   //下界(一次跳躍的最大距離)for(int i=1;i<=n+1;i++){if(i<=n)   //僅輸入1~n,當i=n+1時僅用於尋找lowcin>>dist[i];if(low > dist[i]-dist[i-1])low=dist[i]-dist[i-1];}sort(dist,dist+(n+2));   //根據石頭到S的距離升序排列/*Binary-Search*/while(low<=high){int mid=(low+high)/2;  //對最大跳和最小跳的距離折中,二分尋找mid相對於最優解是偏大還是偏小                       //假設mid是移除m個石頭後的最短距離int delrock=0;    //利用當前的mid值能移除的石頭數int sum=0;   //類比POJ 3273, 這裡是 連續距離的累加值             //當在第i個距離累加後sumfor(int i=1;i<=n+1;){if( (sum+=dist[i]-dist[i-1]) <= mid){i++;delrock++;}else   //當從第i個距離累加到i+k個距離後,若sum>mid,則k個距離作為一段{i++;sum=0;  //sum置0,從第i+k+1個距離重新累加}}if(delrock<=m)   //本題痛點之一:即使delrock==m也不一定找到了最優解low=mid+1;   //用當前mid值移除的石頭數小於規定數,說明mid偏小else             high=mid-1;  //反之mid偏大}/*Output & Relax*/cout<<low<<endl;delete dist;}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.