Recently I came across this, here is an excerpt from it,
This is another problem about Indraneel's library. His library has one long shelf. His books are numbered and he identifies the books by their number. Each book has a distinct number.
He has lost many books, since many of his friends borrow his books and never bother to return them. He does not want to lose any more books and has decided to keep a record of all books that he lends to his friends. To make the task of borrowing a book a little difficult, he has given the following instructions to his friends: when they borrow a book, they must record in a register its position from the left among the books currently on the shelf.
Suppose there are 5 books in the library and they are arranged as follows:
26 1 42 15 3
If someone walks in and borrows the book 42, then he will record 3 in the register because this book is the third from the left on the shelf. Now the shelf looks like this:
26 1 15 3
If the next person borrow the book 3, he writes down 4 in the register since this is currently the fourth book from the left on the shelf, and so on.
Indraneel knows the initial arrangement of the books in his library at the time that he introduced the register system. After a while he examines his register and would like to know which books have been borrowed. Your task is to write a program to help Indraneel solve this problem.
My approach is count from left if the value of the book is -1 then skip the the book , when the count is equal to the count of the book then print the name of the book and make that value -1.But this approach though correct is giving time limit exceeded on a handful of testcases. Anyone having a better approach for this problem?
Here is the code:
#include <iostream>
#include <vector>
int main(){
//Input for the number books with the values
int m;
std::cin >> m;
std::vector<int>books(m);
for(int i=0;i<m;i++){
std::cin>>books[i];
}
//Input for the dispatches made
int n;
std::cin >> n;
std::vector<int>taken(n);
for(int i=0;i<n;i++){
std::cin >> taken[i];
}
for(int i=0;i<n;i++){
int bookNum = taken[i]-1; //Get the position of book needed
int k=0;
for(int j=0;j<m;j++){ //Go through the book array
if(books[j] != -1){
if(k == bookNum){
std::cout << books[j] << std::endl; //Display the name if the k is equal
books[j] = -1;
break;
}
k++; //Increment k if the value of the book is not negative
}
}
}
return 0;
}
Here are the testcases.