-
Notifications
You must be signed in to change notification settings - Fork 6
/
05_Book_Allocation.cpp
93 lines (73 loc) · 1.48 KB
/
05_Book_Allocation.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#define fastio ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
bool checkReading(int arr[], int n, int m, int page)
{
int count = 0;
for(int i=0; i<n; i++)
{
count = count+arr[i];
if(count>page)
{
count = arr[i];
m--;
}
}
if(m<=0)
{
return false;
}
return true;
}
int minimumPages(int arr[], int n, int m)
{
//Now since you need to return minimum pages
//hence your search area is pages
//At least one student will read the maximum number of pages
//from the array.
//In worst case, a student may have to read all the pages.
//Therefore search area becomes
//max(Arr) to total number of pages
//Now apply binary search and check if each one can read
//atleast those many pages
int s = arr[n-1];
int e = 0;
for(int i=0; i<n; i++)
{
e = e + arr[i];
}
int ans = 0;
while(s<=e)
{
int mid = (s+e)>>1;
if(checkReading(arr, n, m, mid))
{
ans = mid;
e = mid-1;
}
else
{
s = mid+1;
}
}
return ans;
}
int main()
{
int t;
fastio
cin>>t;
while(t--)
{
int n, m;
cin>>n>>m;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int res = minimumPages(arr, n, m);
cout<<res<<"\n";
}
return 0;
}