-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbookAllocation.cpp
More file actions
56 lines (50 loc) · 1.1 KB
/
bookAllocation.cpp
File metadata and controls
56 lines (50 loc) · 1.1 KB
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
#include <bits/stdc++.h>
using namespace std;
bool isPossible(vector<int> &v, int n, int m, int mid) {
int studentCount = 1;
int pageSum = 0;
for (int i = 0; i < n; i++) {
if (pageSum + v[i] <= mid) {
pageSum += v[i];
}
else {
studentCount++;
if (studentCount > m || v[mid] > mid) {
return false;
}
pageSum = v[i];
}
}
return true;
}
int allocateBooks(vector<int> &v, int n, int m) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += v[i];
}
int st = 0, end = sum, mid;
int ans = -1;
while (st <= end) {
mid = st + (end - st) / 2;
if (isPossible(v, n, m, mid)) {
ans = mid;
end = mid - 1;
}
else {
st = mid + 1;
}
}
return ans;
}
int main()
{
int n, m;
cin >> n >> m;
vector<int> v(n);
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
cout << allocateBooks(v, n, m) << endl;
return 0;
}