AGGRCOW - Aggressive cows SPOJ Solution C++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n,c;
int valid(vector<int> &a,int val){
  int curr=a[0];
  int j=1;
  for(int i=1;i<c;i++){
    while(a[j]-curr<val){j++;if(j==n)return 0;}
    curr=a[j];
  }
  return 1;
}
int main() {  
  ios::sync_with_stdio(0);
  cin.tie(NULL);
  int t;
  cin>>t;
  while(t--){
    cin>>n>>c;
    vector<int> a(n);
    for(int i=0;i<n;i++)
      cin>>a[i];
    sort(a.begin(),a.end());
    int ans=0;
    int low=1,high=(a[n-1]-a[0])/(c-1),mid;
    while(low<=high){
      mid=(low+high)/2;
      if(valid(a,mid)){
        ans=mid;
        low=mid+1;
      }
      else{
        high=mid-1;
      }
    }
    cout<<ans<<'\n';
  }
  return 0;
}

Comments