aggressive cows (binary Search) 

Run Settings
LanguageC++
Language Version
Run Command
//TheShadowGrapher's Code #include <iostream> #include<bits/stdc++.h> #include <queue> #include <vector> #include <set> #include <map> #define f(i,a,b,c) for(int i = a ; i< b ; i+=c ) #define nl "\n" using namespace std; bool checkIf(int key , int a[] , int nstalls , int ncows) { int cs = 0 , i = 1 ,count = 1 ; while(i < nstalls ) { if(abs(a[i]-a[cs]) >= key){ cs = i ; count++ ; } i++ ; if(count >=ncows ) return true ; } return false ; } void anything() { int n ,c ; cin>>n ; cin>>c ; //inputs int a[n] ; int MinDist = 1000001 , maxVal = -1 , minVal = 100000001 , temp; f(i, 0 , n , 1) { cin>>a[i]; if (a[i] > maxVal ) maxVal = a[i] ; if (a[i] <minVal) minVal = a[i] ; if(i) { if(temp-a[i] < MinDist) MinDist = temp-a[i] ; temp = a[i]; } else temp = a[i] ; } sort(a, a+n) ; int low = MinDist , high = maxVal-minVal , ans = 0 ; while(low <=high) { int mid = (low +high)/2 ; if(checkIf(mid , a , n, c )) { ans = mid ; low = mid +1 ; } else high = mid-1 ; } cout<<ans<<nl; } int main() { //testcases int t ; ios_base::sync_with_stdio(false); cin.tie(NULL); cin>>t ; while(t--) { anything(); } return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines