The algorithm for moving an element to the beginning of the list by time O (m sqrt (n))

Given the number n , the source list ( that is, the source list is sorted and contains elements from 0 to n-1 ):

[0, 1, 2, ... n - 1]

Input is a sequence of numbers m . For each input number, move the number to the top of the list and print the index of that number.

For instance:

n = 5:

Input:

3 3 4 2

Conclusion:

3 0 4 4

Explanation: For n = 5, the initial list

[0, 1, 2, 3, 4]

First move 3 to the front. Index 3 on the list is 3.

[3, 0, 1, 2, 4]

Then we again move 3 forward. Since it is already in front, the index is 0.

[3, 0, 1, 2, 4]

Then we move 4 to the front. Index 4 is 4.

[4, 3, 0, 1, 2]

Finally, we move 2 forward. Index 2 is 4.

[2, 4, 3, 0, 1]

O (mn) , . O (m sqrt (n)).

, , , - , . , ?

+4
2

O (m√n) , O (m log n) - - (, - ) .

, :

  • " ".
    • (= ) node O (log n), .
  • , ( 0 n-1), node "". , node , , node ( 0, -1, -2 ..)., , "".
    • node , .
    • , node, "", O (log n) .
  • node "". ( 0 n-1, .)
    • , node, , O (log n) .
    • ; .
  • , "" , - , . O (log n) , , , , .

O (n) node O (log n).

, , . , . , - - ? (, , , - - "", java.util.TreeMap std::map ?)

+3

. INDICES , 0, √n, 2√n,..., (n-1) √n. node IDX ( √n 0, √n 1,..., , ).

NODES , . .

node , O (√n).

node 5:

  • NODES[5] node, 5.
  • : count from INDICES[NODES[5]->IDX], 5. O (√n).
  • node . O (1).
  • INDICES IDX . O (√n) INDICES ( , INDICES[i] = INDICES[i]->PREV), O (√n) , IDX (INDICES[i]->IDX = INDICES[i]->IDX + 1).
+2

Source: https://habr.com/ru/post/1685837/


All Articles