forked from MukulCode/CodingClubIndia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Book_Allocation_Problem.cpp
70 lines (62 loc) · 1.54 KB
/
Book_Allocation_Problem.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
/*
Given an array ‘pages’ of integer numbers, where ‘pages[i]’ represents the number of pages in the ‘i-th’ book. There are ‘m’ number of students, and the task is to allocate all the books to their students.
Allocate books in a way such that:
1. Each student gets at least one book.
2. Each book should be allocated to a student.
3. Book allocation should be in a contiguous manner.
You have to allocate the books to ‘m’ students such that the maximum number of pages assigned to a student is minimum.
*/
#include <bits/stdc++.h>
using namespace std;
bool isPossible(int arr[], int n, int m, int mid)
{
int studentCount = 1;
int pageSum = 0;
for (int i = 0; i < n; i++)
{
if (pageSum + arr[i] <= mid)
pageSum += arr[i];
else
{
studentCount++;
if (studentCount > m || arr[i] > mid)
{
return false;
}
pageSum = arr[i];
}
}
return true;
}
int findPages(int arr[], int n, int m)
{
int sum = 0;
for (size_t i = 0; i < n; i++)
{
sum += arr[i];
}
int s = 0, e = sum;
int ans = -1;
while (s <= e)
{
int mid = s + (e - s) / 2;
if (isPossible(arr, n, m, mid))
{
ans = mid;
e = mid - 1;
}
else
{
s = mid + 1;
}
}
return ans;
}
int main()
{
int arr[] = {10, 20, 30, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int m = 2;
cout << findPages(arr, n, m);
return 0;
}