Skip to content

Commit f15ac24

Browse files
solved on 02/10/23
1 parent f3e2eed commit f15ac24

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

GFG_AgressiveCows.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
bool isPossibleSol(vector<int> &stalls, int k, int mid)
5+
{ // predicate function
6+
// can we place k cows with atleast mid distance between cows' stalls?
7+
int cnt = 1; // count of cows
8+
int pos = stalls[0];
9+
for (int i = 0; i < stalls.size(); i++)
10+
{
11+
if (stalls[i] - pos >= mid)
12+
{ // if min. dist. is same is greater than mid, then place the cow
13+
cnt++;
14+
pos = stalls[i]; // 1 more cow has been placed
15+
}
16+
if (cnt == k)
17+
{
18+
return true;
19+
}
20+
}
21+
return false;
22+
}
23+
24+
int solve(int n, int k, vector<int> &stalls)
25+
{
26+
sort(stalls.begin(), stalls.end());
27+
int start = 0;
28+
int end = stalls[stalls.size() - 1] - stalls[0];
29+
30+
int ans = -1;
31+
while (start <= end)
32+
{
33+
int mid = (start + end) / 2;
34+
if (isPossibleSol(stalls, k, mid))
35+
{
36+
ans = mid;
37+
start = mid + 1;
38+
}
39+
else
40+
{
41+
end = mid - 1;
42+
}
43+
}
44+
return ans;
45+
}
46+
47+
int main()
48+
{
49+
int n, k;
50+
cout << "Enter the number of stalls: ";
51+
cin >> n;
52+
cout << "Enter the number of cows: ";
53+
cin >> k;
54+
vector<int> stalls(n);
55+
cout << "Enter the stalls' positions: ";
56+
for (int i = 0; i < n; i++)
57+
{
58+
cin >> stalls[i];
59+
}
60+
cout << "The maximum min. distance between cows' stalls is: " << solve(n, k, stalls) << endl;
61+
return 0;
62+
}

GFG_AgressiveCows.exe

2.88 MB
Binary file not shown.

0 commit comments

Comments
 (0)