GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Place cows such that minimum difference is maximized

You are given an array of integers which represents positions available and an integer c(cows).

Now you have to choose c positions such that minimum difference between cows is maximized.

For example,

1 3 5 8 10

c=3

output: 4

1 5 10

asked Aug 5, 2016 by Gokul Ram 1

1 Answer

#include<bits/stdc++.h>


/*
I have done binary search on the minimum possible maximum distance between two positions of the given
array.It ranges from 0 to a[n-1]-a[0] after sorting array a.Then finding the minimum possible maximum
distance by doing binary search.The check function returns true if it is possible to chose at least c 
elements from the array that differ by dis distances , false otherwise. 
*/


#define pb push_back
#define mp make_pair
#define maxi 111111
#define ll long long
#define mod 1e9+7

using namespace std;

ll a[maxi];
vector<ll>ans;

bool check(ll dis,ll c,ll n,int flag){
    ll pre=a[0];
    ll i,cnt=1;
    if(flag==1){
        ans.clear();
        ans.pb(a[0]);
    }
    for(i=1;i<n;i++){
        if(a[i]-pre>=dis){
            cnt++;
            pre=a[i];
            if(flag==1 && cnt<=c){
                ans.pb(a[i]);
            }
        }
    }
    if(cnt>=c)return true;
    else return false;
}

int main()
{
    ll n,l,r,mid,i,c;
    cin>>n>>c;
    for(i=0;i<n;i++){
        cin>>a[i];
    }

    sort(a,a+n);
    l=0;
    r=a[n-1]-a[0];

    while(l<r-1){
        mid=l+(r-l)/2;

        if(check(mid,c,n,0)){
            l=mid;
        }
        else{
            r=mid-1;
        }
    }

    if(check(l+1,c,n,1)){
        cout<<l+1<<endl;
        for(i=0;i<ans.size();i++){
            cout<<ans[i]<<" ";
        }
        cout<<endl;
        return 0;
    }
    else if(check(l,c,n,1)){
        cout<<l<<endl;
        for(i=0;i<ans.size();i++){
            cout<<ans[i]<<" ";
        }
        cout<<endl;
        return 0;
    }

}

 

answered Nov 25, 2016 by ravikiran0606
edited Nov 25, 2016 by ravikiran0606
...