#P6319. Restore Linked List

    ID: 19535 Type: Default 1000ms 256MiB

Restore Linked List

Restore Linked List

You are given a linked list of (n) nodes with values (1,2,\ldots,n) arranged from left to right. Two operations can be performed on this list:

  1. (A\ x\ y): Move node (x) to before node (y).
  2. (B\ x\ y): Move node (x) to after node (y).

For example, consider a list with 6 nodes:

Initial list

After performing operation (A\ 1\ 4), the list becomes:

After A operation

Then, performing (B\ 3\ 5), the list becomes:

After B operation

Mirko played with the list for several hours and recorded each operation. When he finally decided to restore the original list (i.e. (1,2,\ldots,n)), he realized that he only knew the final order of the nodes. Your task is to restore the list to its sorted order by performing a minimum number of operations. It can be shown that the minimum number of operations is equal to (n - |LIS|), where (|LIS|) is the length of a longest increasing subsequence of the final order. For every node that is not part of this subsequence, reposition it to immediately follow its predecessor (with node (1) moved to the front if necessary).

inputFormat

The first line contains an integer (n) ((1 \le n \le 10^5)), which is the number of nodes. The second line contains (n) distinct integers representing the final order of nodes in the linked list.

outputFormat

The first line should contain the minimum number of operations (m). Each of the next (m) lines should describe one operation in the format described above.

sample

6
2 1 4 3 6 5
3

A 1 2 B 3 2 B 5 4

</p>