If you just need the last number, it's known as Josephus problem and there're well-known formulas for computing the answer in O(N)
time.
I don't know if one can adapt it to run a full simulation, so I'll describe a straightforward O(N log N)
solution here:
Let's keep all numbers in a treap with implicit keys. We need to find the k
-th element and delete it at each step (in fact, there can be a shift, so it's more like (cur_shift + k) % cur_size
, but it doesn't really matter). A treap can do it. We just need to split it into 3 parts [0, k - 1]
, [k, k]
and [k + 1, cur_size - 1]
, print the number in the node that corresponds to the second part and merge the first and last part back together. It requires O(log N)
time per step, so it should be good enough for the given constraints.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…