Given an array with a length of N, it is composed of {1, 2, 3} And is arranged as the minimum number of moves without downgrading the sequence.
Analysis: Obtain the numbers of 1, 2, and 3 respectively. Count [1], Count [2], Count [3]; then, you can know the region of each element after the arrangement;
Next, we need to consider the areas 1 and 2;
One exchange, the ability to return to their own region, should be the best exchange, so that we will give priority to the exchange after the two can return to their own position
For (INT I = 1; I <= count [1] + Count [2]; I ++ ){
If (T [I] = 3) A [3] ++;
Else if (T [I] = 2 & I <= count [1]) A [1] ++;
Else if (T [I] = 1 & I> count [1]) A [2] ++;
}
From aboveCodeTake the smaller one in a [1] and a [2]. We will find t = min (A [1], a [2]). the value is the number of direct exchanges between 1 and 2. The result of T-switching is that T 1 and T 2 are returned to their respective regions. Next, 3 In areas 1 and 2 must be exchanged with the following three regions for a [3] exchange (of course, you should try your best to switch yourself back to the region, but the total number of times is still a [3] times), 3 is all returned to the region, you will find a data first, at this time, if there are still 2 misplaced numbers in area 1, it is because a [1] and a [2] are not equal, the number of times to be exchanged is ABS (A [1]-A [2]);
Finally, the minimum number of exchanges is a [3] + max (A [1], a [2]).
/* ID: nanke691lang: C ++ task: sort3 */# include <fstream> # include <iostream> # include <algorithm> # include <string. h> using namespace STD; int main () {freopen ("sort3.in", "r", stdin); freopen ("sort3.out", "W", stdout ); int count [4], a [4], t [1001], X, n, k = 0; memset (count, 0, sizeof (count); memset (, 0, sizeof (a); scanf ("% d", & N); While (n --) {scanf ("% d", & X ); count [x] ++; t [++ K] = x ;}for (INT I = 1; I <= count [1] + Count [2]; I ++) {If (T [I] = 3) A [3] ++; else if (T [I] = 2 & I <= count [1]) A [1] ++; else if (T [I] = 1 & I> count [1]) A [2] ++ ;} cout <A [3] + max (A [1], a [2]) <Endl ;}