Problem E
Exchange Students

Silhouettes via Freepik
A group of $n$ exchange students at Reykjavik University is lining up to get their group photo taken. From left to right, the heights of the students are $g_1, g_2, \ldots , g_ n$. However, the photographer would like to rearrange the students such that the order of their heights becomes $h_1, h_2, \ldots , h_ n$. In order to do this, the photographer will repeatedly exchange two exchange students. Two exchange students can only be exchanged if they can see each other, that is, if every student in between them has strictly smaller height than the two students to be exchanged.

Determine the minimum number of exchanges needed to arrange the students in the photographer’s preferred order, and find a suitable sequence of exchanges of this minimal length. The photographer only has time for at most $2\cdot 10^5$ exchanges. If more are needed, you only need to determine the first $2\cdot 10^5$ exchanges.


The input consists of:

  • One line with an integer $n$ ($1\leq n \leq 3\cdot 10^5$), the number of students.

  • One line with $n$ integers $g_1, g_2, \ldots , g_ n$ ($1\leq g_ i\leq 10^9$), the heights of the students.

  • One line with $n$ integers $h_1, h_2, \ldots , h_ n$ ($1\leq h_ i\leq 10^9$), the order of heights the photographer prefers.

It is guaranteed that $(h_1, \ldots , h_ n)$ is a permutation of $(g_1, \ldots , g_ n)$.


First output an integer $s$, the minimum number of exchanges needed. Then print $\min (s, 2\cdot 10^5)$ exchanges, each consisting of two integers $i$ and $j$, the one-based positions of the students that must be exchanged in this step.

If there are multiple valid solutions, you may print any one of them.

Sample Input 1 Sample Output 1
2 1 3
3 1 2
1 3
Sample Input 2 Sample Output 2
6 7 5 9 6
9 6 7 6 5
3 4
4 5
1 2
1 3

Please log in to submit a solution to this problem

Log in