forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AllocateBooks.cpp
105 lines (83 loc) · 2.19 KB
/
AllocateBooks.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
94
95
96
97
98
99
100
101
102
103
104
105
// Allocate Books
// Idea:
// We need to make sure chapters are assigned to Ayush in such a way that max numbers of chapters read by him in a single day is minimized.
/*
Input: n = 2, m = 4
10 20 10 30
Approach:
max number of chapters assigned to him in a single day is upper bounded by total number of chapters.
sum of time required to read all the chapters = (10+20+10+30) = 70
Min value will be the max time required to read a chapter : 30
i.e our answer cannot be less than the max page in a book.
Hence our answer must lie in the range [ 30, 70]. we will apply binary search in this range.
10 20 10 30
x = (30+70)/2 = 50 res = 50 (feasible solution)
10+20 = 30 && 10+30 = 40
10+20+10 = 40 && 30
to find min solution
x = (30+49)/2 = 39 (not feasible)
10+20 = 30 && 30+10=40 > 39
10+20+10 = 40 > 39
since for 39 solution is not feasible then for any lower value solution would not be feasible.
so move to right of 39
x = (40+49)/2 = 44 res = 44 (feasible)
10+20 = 30 && 30+10=40
10+20+10 = 40 && 30
go to left half of 44
x = (40+43)/2 = 41, res = 41(feasible)
10+20 = 30 && 30+10=40
10+20+10 = 40 && 30
go to left half of 41
x = (40+40)/2 = 40 , res = 40
10+20 = 30 && 30+10=40
10+20+10 = 40 && 30
*/
#include <bits/stdc++.h>
using namespace std;
bool isFeasible(vector<int> &time, int k, long long mid)
{
long long req = 1, sum = 0;
for(auto x: time)
{
if(x > mid) return false;
else if(sum+x > mid)
{
req++;
sum = x;
}
else
sum += x;
}
return (req <= k);
}
long long allocateBooks(int n, int m, vector<int> time)
{
long long sum = 0;
int mx = 0;
for(int i = 0; i < m; i++)
{
sum += time[i];
mx = max(mx, time[i]);
}
long long low = mx, high = sum, res = 0;
while(low <= high)
{
long long mid = (low+high)/2;
if(isFeasible(time, n, mid))
{
res = mid;
high = mid-1;
}
else
low = mid+1;
}
return res;
}
int main(){
int n, m;
cin>>n>>m;
vector<int> time(m);
for(int i = 0; i < m; i++) cin>>time[i];
cout<<allocateBooks(n, m, time);
return 0;
}