Your algorithm has complexity O(N^2) , so for arrays of size 10^5 it takes too much time to execute. I am trying to describe a better solution:
We have N numbers. Allows you to call the return array I To solve this problem, we need to know where the K-th position is from the end of the permutation, which is still free (allows calling this function F(K) ). First, put the number N in position F(I[N] + 1) , then put the number N-1 in position F(I[N-1] + 1) , etc.
F can be calculated as follows: declare an array M size N : 1 1 1 ... 1 , determine S(X) = M[1] + M[2] + ... + M[X] . S is called the prefix sum. F(K) equal to N plus 1 minus such a lower X such that S(X) = K Each time we put the number Z in the position N + 1 - X(for K = I[Z] + 1) , we put a zero on M[X] . To find X faster than in O(N) , I can suggest using Binary Indexed Trees to calculate the prefix sums in O(logN) time and Binary Search to find an X such that S(X) is equal to some predetermined value.
The overall complexity of such an algorithm is O(N(log(N))^2) . This is an implementation in Ruby (you can play with it directly in ideon: change the input, start and check the output):
A solution with O(N(log(N))) exists as well. It uses a kind of binary search tree : we create a BST with numbers 1, 2, 3, ... N on the vertices, then we can find the K-th number by value in O(log(N)) and also delete the vertices in O(log(N)) .
There may also be a solution with std :: set , but I can't think about it right now.
PS. I can also suggest you read some books about algo and olympiads, such as Skienna (task programming) or Cormen (introduction to algorithms)
PPS Sorry for the wrong solution that I described earlier
907th
source share