Skip to content

Commit 309bd20

Browse files
authored
Aggressive Cows Solution Added
1 parent 7a8b4f4 commit 309bd20

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Hacker Blocks/Aggressive Cows.cpp

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/* Hacker Blocks */
2+
/* Title - Aggressive Cows */
3+
/* Created By - Akash Modak */
4+
/* Date - 27/06/2020 */
5+
6+
// 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).
7+
8+
// 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 wants 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?
9+
10+
// Input Format
11+
// First line contains N and C, separated by a single space, representing the total number of stalls and number of cows respectively. The next line contains N integers containing the indexes of stalls.
12+
13+
// Constraints
14+
// 2 <= N <= 100,000
15+
// 0 <= xi <= 1,000,000,000
16+
// 2 <= C <= N
17+
18+
// Output Format
19+
// Print one integer: the largest minimum distance.
20+
21+
// Sample Input
22+
// 5 3
23+
// 1 2 8 4 9
24+
// Sample Output
25+
// 3
26+
// Explanation
27+
// Problem Credits - (Spoj)[http://www.spoj.com/problems/AGGRCOW/]
28+
29+
#include<iostream>
30+
#include<algorithm>
31+
using namespace std;
32+
bool checkCows(int a[],int n,int c,int minSep){
33+
int lastCow=a[0];
34+
int count = 1;
35+
for(int i=1;i<n;i++){
36+
if(a[i]-lastCow>=minSep){
37+
lastCow = a[i];
38+
count++;
39+
40+
if(count==c)
41+
return true;
42+
}
43+
}
44+
return false;
45+
}
46+
void search(int n,int c,int a[]){
47+
int ans = 0;
48+
int start = a[0];
49+
int end = a[n-1] - a[0];
50+
while(start<=end){
51+
int mid = (start+end)/2;
52+
bool check = checkCows(a,n,c,mid);
53+
54+
if(check){
55+
start = mid+1;
56+
ans= mid;
57+
58+
}
59+
else
60+
end=mid-1;
61+
}
62+
cout<<ans<<endl;
63+
}
64+
int main() {
65+
int n,c;
66+
cin>>n>>c;
67+
int a[n];
68+
for(int i=0;i<n;i++)
69+
cin>>a[i];
70+
sort(a,a+n);
71+
search(n,c,a);
72+
return 0;
73+
}

0 commit comments

Comments
 (0)