-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathboats.cpp
More file actions
78 lines (65 loc) · 1.52 KB
/
boats.cpp
File metadata and controls
78 lines (65 loc) · 1.52 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
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
struct boat {
int length;
int ringPosition;
bool operator<(boat &o) const {
return ringPosition < o.ringPosition;
}
};
void solve() {
int n; cin >> n;
vector<boat> boats(n);
int boatLength, ringPosition;
for (int i = 0; i < n; ++i) {
cin >> boatLength;
cin >> ringPosition;
boats[i] = boat({boatLength, ringPosition});
}
sort(boats.begin(), boats.end());
int end = numeric_limits<int>::min();
int count = 0;
int lastIndex = -1;
while (true) {
// Initialization
int i = lastIndex + 1;
int firstEnd = numeric_limits<int>::max();
int firstEndIdx = -1;
while (i < n) {
ringPosition = boats[i].ringPosition;
boatLength = boats[i].length;
int boatStart = max(end, ringPosition - boatLength);
if (boatStart > ringPosition) { // Not a valid placement
++i;
continue;
}
if (boatStart > firstEnd) { // Can not be optimal
break;
}
int currentEnd = boatStart + boatLength;
if (currentEnd < firstEnd) { // New optimum
firstEnd = currentEnd;
firstEndIdx = i;
}
++i;
}
// No more boats possible
if (firstEndIdx == -1) {
break;
}
// Take boat and find next boat
lastIndex = firstEndIdx;
end = firstEnd;
++count;
}
cout << count << endl;
}
int main() {
int t; cin >> t;
for (int i = 0; i < t; ++i) {
solve();
}
}