Commuting Functions

Time limit3sMemory limit256 MB

Summary
Given a permutation f on {1..n}, construct the lexicographically smallest permutation g that commutes with f under composition.
Level

Medium6 of 10

Topics
Graph, Greedy, Math
Solved
No attempts yet

Statement

Two functions ff and gg (f,g:X→Xf, g : X \to X) commute if and only if f(g(x))=g(f(x))f(g(x)) = g(f(x)) for every x∈Xx \in X. For example, f(x)=x+1f(x) = x + 1 and g(x)=x−2g(x) = x - 2 commute, whereas f(x)=x+1f(x) = x + 1 and g(x)=2xg(x) = 2x do not.

Every function hh (h:Nn→Nnh : N_n \to N_n, where Nn={1,2,…,n}N_n = \{1, 2, \ldots, n\} and nn is a positive integer) can be written as a value list — a list whose ii-th element equals h(i)h(i). For example, the function h(x)=⌈x/2⌉h(x) = \lceil x/2 \rceil from N5N_5 to N5N_5 has the value list [1,1,2,2,3][1, 1, 2, 2, 3].

Value lists are ordered lexicographically: the list [a1…an][a_1 \ldots a_n] is smaller than the list [b1…bn][b_1 \ldots b_n] if and only if there is an index kk with ak<bka_k < b_k and al=bla_l = b_l for every index l<kl < k.

A function ff (f:X→Xf : X \to X) is bijective if for every y∈Xy \in X there is exactly one x∈Xx \in X with f(x)=yf(x) = y.

Given a bijective function ff (f:Nn→Nnf : N_n \to N_n), find the function gg that commutes with ff and has the lexicographically smallest possible value list.

Input

The first line contains a single integer nn — the number of elements in the value list of the bijective function ff (1≤n≤200 0001 \le n \le 200\,000).

The second line contains the value list of ff: nn integers that form a permutation of 1,2,…,n1, 2, \ldots, n.

Output

Print a single line with nn integers — the value list of the function gg that commutes with ff and has the lexicographically smallest value list.

Examples4

  1. Example 1

    Input
    10
    1 2 3 4 5 6 7 8 9 10
    
    Expected output
    1 1 1 1 1 1 1 1 1 1
    
  2. Example 2

    Input
    10
    2 3 4 5 6 7 8 1 9 10
    
    Expected output
    1 2 3 4 5 6 7 8 9 9
    
  3. Example 3

    Input
    1
    1
    
    Expected output
    1
    
  4. Example 4

    Input
    2
    2 1
    
    Expected output
    1 2