-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem69.cpp
More file actions
68 lines (59 loc) · 1.29 KB
/
problem69.cpp
File metadata and controls
68 lines (59 loc) · 1.29 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
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
class ParcelPacking {
vector<int> parcels;
int N, K;
public:
void readInput() {
cin >> N >> K;
if (N < 1 || N > 1e5 || K < 1 || K > N) {
cout << "!! Invalid input range !!" << endl;
exit(1);
}
parcels.resize(N);
for (int i = 0; i < N; i++) {
cin >> parcels[i];
if (parcels[i] < 1 || parcels[i] > 1e4) {
cout << "!! Invalid parcel weight !!" << endl;
exit(1);
}
}
}
bool isPossible(int maxWeight) {
int count = 1, currentSum = 0;
for (int w : parcels) {
if (currentSum + w <= maxWeight) {
currentSum += w;
} else {
count++;
currentSum = w;
if (count > K) return false;
}
}
return true;
}
int findMinMaxWeight() {
int left = *max_element(parcels.begin(), parcels.end());
int right = accumulate(parcels.begin(), parcels.end(), 0);
int ans = right;
while (left <= right) {
int mid = left + (right - left) / 2;
if (isPossible(mid)) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
void display() {
cout << findMinMaxWeight() << endl;
}
};
int main() {
ParcelPacking pp;
pp.readInput();
pp.display();
return 0;
}