-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem64.cpp
More file actions
40 lines (34 loc) · 893 Bytes
/
problem64.cpp
File metadata and controls
40 lines (34 loc) · 893 Bytes
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
#include <iostream>
#include <vector>
#include <algorithm> // for lower_bound
using namespace std;
class MagicalBookshelf {
public:
vector<int> books;
int target;
void readInput() {
cout << "Enter book numbers: ";
int num;
while (cin >> num) {
books.push_back(num);
if (cin.peek() == '\n') break;
}
cout << "Enter the number of the new book: ";
cin >> target;
}
int findInsertPosition() {
// Use lower_bound for binary search: returns first index >= target
auto pos = lower_bound(books.begin(), books.end(), target);
return pos - books.begin();
}
void print(int index) {
cout << "Position: " << index << endl;
}
};
int main() {
MagicalBookshelf mb;
mb.readInput();
int index = mb.findInsertPosition();
mb.print(index);
return 0;
}