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);