This is mainly because the minimum price is required during the exchange.
First, find the same number in the ring and connect it to the same column.
1. First behavior Starting sequence 2 behavior target sequence
Swap the smallest vertex in a ring with the number of points
Last Switch 3 2
Or the smallest number in the sequence and the smallest number in the ring (Boat problem ?)
In this way, the optimal solution is obtained.
Ans + = min (sizi-2) * mini + sumi,
(Sizi + 1) * minn + mini + sumi
[Cpp]
# Include <cstdio>
# Include <cmath>
# Include <iostream>
# Include <cstdlib>
# Include <cstring>
# Include <functional>
# Include <algorithm>
Using namespace std;
# Define MAXN (10000 + 10)
# Define MAXAI (100000 + 10)
Int n, a [MAXN], a2 [MAXN], hpos [MAXAI], ans = 0;
Bool B [MAXN];
Int main ()
{
// Freopen ("cowsorting. in", "r", stdin );
Scanf ("% d", & n );
For (int I = 1; I <= n; I ++) scanf ("% d", & a [I]);
Memcpy (a2, a, sizeof ());
Sort (a2 + 1, a2 + 1 + n, less <int> ());
Int minn = a2 [1];
Memset (B, false, sizeof (B ));
For (int I = 1; I <= n; I ++)
Hpos [a [I] = I;
For (int I = 1; I <= n; I ++)
{
// Cout <a2 [I] <''<a [I] <endl;
If (! B [I] & a2 [I]! = A [I])
{
B [I] = 1;
Int mini = a [I], start = I, sizi = 1, sumi = a [I];
Int now = hpos [a2 [I];
While (now! = Start)
{
B [now] = 1;
Sizi ++;
Sumi + = a [now];
Mini = min (mini, a [now]);
Now = hpos [a2 [now];
}
Ans + = min (sizi-2) * mini + sumi, (sizi + 1) * minn + mini + sumi );
}
}
/// 000
// For (int I = 1; I <= n; I ++) printf ("% d", a2 [I]);
/// 000
Printf ("% d \ n", ans );
// While (1 );
Return 0;
}