-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP714.cpp
74 lines (72 loc) · 1.63 KB
/
P714.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
bool ok(const long max, const int m, const int k, long const * const pages) {
//cerr << "Trying max=" << max;
long stack = 0;
int personI = 0;
FORI(m) {
stack += pages[i];
if(stack > max) {
stack = pages[i];
++personI;
if(personI >= k) {
//cerr << " Reached person " << k << "=> false" << endl;
return false;
}
}
}
//cerr << " OK" << endl;
return true;
}
int main() {
long pages[500];
FORCAS {
int m, k; cin >> m >> k;
long maxPages = -1, sumPages = 0;
FORI(m) {
cin >> pages[i];
maxPages = MAX(pages[i], maxPages);
sumPages += pages[i];
}
long lower = maxPages-1; // too little
long upper = sumPages; // will have the result when done.
while(lower < upper-1) {
long mid = (upper+lower)/2;
if(ok(mid, m, k, pages))
upper = mid;
else
lower = mid;
}
//cerr << "m=" << m << ", k=" << k << ", Lower: " << lower << ", Upper: " << upper << endl;
// Output:
stack<int> booksPrScriber;
long sum = 0;
int cnt = 0;
FORI(m) {
sum += pages[m-1-i];
++cnt;
int booksLeft = m-i;
int peopleLeft = k-(int)booksPrScriber.size();
if(sum > upper || booksLeft < peopleLeft) {
booksPrScriber.push(cnt-1);
cnt = 1;
sum = pages[m-1-i];
}
}
booksPrScriber.push(cnt);
int bookIdx = 0;
bool any = false;
while(!booksPrScriber.empty()) {
int booksForThis = booksPrScriber.top();
booksPrScriber.pop();
if(any)
cout << " /";
FORI(booksForThis) {
if(any)
cout << " ";
cout << pages[bookIdx++];
any = true;
}
}
cout << endl;
}
return 0;
}