-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA32.cpp
More file actions
65 lines (50 loc) · 1.68 KB
/
A32.cpp
File metadata and controls
65 lines (50 loc) · 1.68 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
57
58
59
60
61
62
63
64
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
// Function to check if the allocation is possible
bool isPossible(const vector<int>& books, int n, int m, int maxPages) {
int studentsRequired = 1;
int currentSum = 0;
for (int i = 0; i < n; ++i) {
if (books[i] > maxPages) return false; // Single book exceeds maxPages
if (currentSum + books[i] > maxPages) {
studentsRequired++;
currentSum = books[i];
if (studentsRequired > m) return false;
} else {
currentSum += books[i];
}
}
return true;
}
// Function to find the minimum of the maximum number of pages
int allocateBooks(const vector<int>& books, int n, int m) {
if (m > n) return -1; // Not enough books for all students
int start = *max_element(books.begin(), books.end());
int end = accumulate(books.begin(), books.end(), 0);
int result = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (isPossible(books, n, m, mid)) {
result = mid;
end = mid - 1; // Try for a smaller maximum
} else {
start = mid + 1; // Increase the maximum
}
}
return result;
}
int main() {
vector<int> books = {10,20,30,40}; // Number of pages in each book
int students = 2; // Number of students
int n = books.size();
int result = allocateBooks(books, n, students);
if (result != -1) {
cout << "The minimum of the maximum pages allocated is: " << result << endl;
} else {
cout << "Book allocation is not possible." << endl;
}
return 0;
}