Test instructions to a sequence of only 1 2 3, the number of 22 interchanges is obtained by an ascending order of 22 interchanges.
Take the sorted sequence as the standard, first find the number of pairs that can make two numbers into the correct position (the first interchange), and then find the number of three numbers (the second exchange) that can only make one number enter the correct position.
The cost of making the first exchange is the number of positions that need to be exchanged (logarithm), the second is the number of the numbers that need to be exchanged, and the cost of 2 for each three number that needs to be exchanged;
/*id:modengd1prog:sort3lang:c++*/#include <iostream> #include <stdio.h> #include <memory.h># Include <algorithm>using namespace Std;int input[1000],order[1000];int State[4][4];//state[i][j] Represents the number of J in the 1 area after sorting (1 is the entire 1 area of the sorted array) int main () {freopen ("sort3.in", "R", stdin); Freopen ("Sort3.out", "w", stdout); int N; scanf ("%d", &n); for (int i=0;i<n;i++) scanf ("%d", &input[i]); memcpy (order,input,sizeof (order)); memset (state,0,sizeof (state)); Sort (order,order+n); int counter=0; for (int i=0;i<n;i++) {state[order[i]][input[i]]++; } int exchange1_3=min (state[1][3],state[3][1]),//1 Zone 3 and 3 in the 1 Exchange, the cost of 1 zone three and 3 of the number of 1 in the minimum value int exchange1_2=min (state[1] [2],state[2][1]);//Ibid. 1 and 2 for int exchange2_3=min (state[2][3],state[3][2]);//Ibid. 2 and 3 for counter=state[1][2]+state[1][3]- EXCHANGE1_2-EXCHANGE1_3;//1 2 3, the number of interchangeable rings counter*=2;//the price of twice times the number of laps counter+=exchange1_2+exchange1_3+exchange2_3;// Plus the operand with a cost of 1 cout<<counter<<Endl return 0;}
Usaco sorting a three-valued Sequence