-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathGFG_BookAllocationProblem.cpp
75 lines (71 loc) · 1.49 KB
/
GFG_BookAllocationProblem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <bits/stdc++.h>
using namespace std;
bool isPossibleSol(int A[], int N, int M, int maxPagesToAllocate)
{
int pageSum = 0;
int cnt = 1;
for (int i = 0; i < N; i++)
{
if (A[i] > maxPagesToAllocate)
{
return false;
}
// if the current student's total pages of all allocated books sum > maxPagesToAllocate
// then allocate the remaining books to further students
if (pageSum + A[i] > maxPagesToAllocate)
{
cnt++;
pageSum = A[i];
if (cnt > M)
{
return false;
}
}
else
{
pageSum += A[i];
}
}
return true;
}
// Function to find minimum number of pages.
int findPages(int A[], int N, int M)
{
if (M > N)
return -1;
int start = 0;
int end = accumulate(A, A + N, 0); // 0 is the initial sum
int ans = -1;
while (start <= end)
{
int mid = (start + end) / 2;
if (isPossibleSol(A, N, M, mid))
{
ans = mid;
end = mid - 1;
}
else
{
start = mid + 1;
}
}
return ans;
}
int main()
{
int t;
cout << "Enter the number of test cases: ";
cin >> t;
while (t--)
{
int N, M;
cin >> N >> M;
int A[N];
for (int i = 0; i < N; i++)
{
cin >> A[i];
}
cout << findPages(A, N, M) << endl;
}
return 0;
}