Dimensional Gate
Time limit1sMemory limit1024 MB
Given a permutation, find the cheapest swaps (cost is the squared gap between swapped gate numbers) that merge all cycles into one.
- Level
Medium7 of 10
- Topics
- Union-find, Greedy, Sorting, Array
- Solved
- No attempts yet
Problem
A dimensional gate is a very convenient means of transport. It looks like an ordinary door, but once you open it and walk through, you arrive in a different space. However, the gates cannot be used in the reverse direction.
ANA country has cities, numbered . Insu, a dimensional magician who handles these gates, made one gate leading to each of cities , numbered each gate , and installed them one per city at random. The gate installed in city has number , and it leads to city .
Insu found that it may be impossible to visit every other city from a given city using only gates. So he plans to cast a spell several times. Each spell swaps the gates of two different cities he chooses. The spell costs mana equal to the square of the difference between the two gate numbers. For example, if city 1 has gate 4 (leading to city 4) and city 4 has gate 6 (leading to city 6), swapping them costs mana.
Find the minimum mana needed to make it possible to visit all other cities from any single city using only gates. Also find how the spells should be cast. The number of spells does not need to be minimal.
Input
The first line contains an integer ().
The second line contains integers (), separated by spaces.
Output
Print the minimum mana and the number of spells , separated by a space. The number of spells does not need to be minimal.
From the second line, print lines in order. Each line contains the two city numbers whose gates are swapped, separated by a space.