POJ 2456 Aggressive cows(二分搜尋最大化最小值),poj2456

來源:互聯網
上載者:User

POJ 2456 Aggressive cows(二分搜尋最大化最小值),poj2456

Aggressive cows
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6372   Accepted: 3181

Description

Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000). 

His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?

Input

* Line 1: Two space-separated integers: N and C 

* Lines 2..N+1: Line i+1 contains an integer stall location, xi

Output

* Line 1: One integer: the largest minimum distance

Sample Input

5 312849

Sample Output

3

題意:

有N個牛舍,第i個在Xi位置,同時有M頭牛,將這M頭牛放於牛舍中,使每頭牛之間距離最大化。

思路:

因為無法直接確定每頭牛的距離,我們可以考慮找到所有牛之間距離的最小值,利用二分從大到小搜尋知道出現滿足crt<N&&X[crt]-X[last]>d,此時的X[crt]-X[last]表示第crt個牛舍

與上一個可放置牛的牛舍距離,若大於d,則說明該crt或crt-1位置的牛舍處於臨界點,可放置牛,若小於d則表示未達臨界點,crt++,繼續搜尋。

代碼如下:

#include<iostream>#include<algorithm>using namespace std;const long MAXN=100000;const long INF=1000000000;long X[MAXN];long N,M;int Tdfs(long d){long last=0;for(int i=1;i<M;i++){long crt=last+1;while(crt<N&&X[crt]-X[last]<d){crt++;}if(crt==N)return 0;last=crt;}return 1;}int main(){int i;long lb,ub,mid;while(cin>>N>>M){lb=0,ub=INF;for(i=0;i<N;i++)cin>>X[i];sort(X,X+N);while(ub-lb>1){mid=(lb+ub)/2;if(Tdfs(mid))lb=mid;elseub=mid;}cout<<lb<<endl;}return 0;}

本題不需使用long long或者_int64,long資料類型足以,long最大支援21億+。另外注意失敗條件“if(crt==N)return 0;”,當返回1時,lb=mid增大d值,反之減小d值。



pascal語言解決Aggressive cows poj2456

二份答案然後線性判斷是否可行
判斷方法:排序後,從前往後,盡量往前取。如果當前節點可以取但不取,那麼之後的解肯定沒有當前的優
做題目應該自己想,但有些情況自己想不到,可以請教前輩;
但程式應該自己編,不能指望別人提供;
演算法知道了就應該自己實現,不會實現那你還是先從基礎題做起吧,練練編程能力而不是分析問題以及做題

二分尋找中 當l可行,l=mid,假設r=l+1,此時陷入死迴圈;
二分尋找中細節改改
l:=1;
r:=tot;
while l<=r do
begin
mid:=(l+r)>>1;
num:=get(mid);
if num>=m then l:=mid+1 else r:=mid-1;
end;
writeln(r);
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.