Description
Sorting is a very frequent computational task. Now consider sorting problems with up to three values. A practical example is when we give a winner of a competition the gold and silver bronze medal order. The possible values in this task are only three and 3. We put him in ascending order by means of an exchange. Write a program that calculates the minimum number of exchanges required in ascending order, given a sequence of numbers made up of a series of a.
Input
Line 1:n (1 <= N <=) Lines 2-n+1: One number per row, total N rows. (1.. 3)
Output
A total of one row, a number. Represents the minimum number of exchanges required to rank in ascending order.
Sample Input
9221333231
Sample Output
4
Exercises
First count the number of a[1, then determine how many non-1 elements of the former (1), and then find a to a[1]+a[2] how many 3 and a[1]+a[2] to n how many 2, two regions of 1 have and the first region of the non-1 element exchange. Finally, find the largest value in the latter two areas.
The code is as follows:
1#include <iostream>2#include <cstdio>3#include <cstdlib>4#include <cstring>5#include <string>6#include <cmath>7#include <map>8#include <stack>9#include <vector>Ten#include <queue> One#include <Set> A#include <algorithm> - #defineMax (A, B) (A>B?A:B) - #defineMin (A, b) (A<B?A:B) the #defineSwap (A, b) (A=a+b,b=a-b,a=a-b) - #defineX (sqrt (5) +1)/2.0 - #defineMAXN 320007 - #defineN 100000000 + #defineINF 0x3f3f3f3f - #definePI ACOs (-1) + #defineLowbit (x) (x& (×)) A #defineRead (x) scanf ("%d", &x) at #definePut (x) printf ("%d\n", X) - #definememset (x, y) memset (x,y,sizeof (×)) - #defineDebug (x) cout<<x<< "" <<endl - #defineLson I << 1,l,m - #defineRson I << 1 | 1,m + 1,r - #defineMoD 1000000009 in #defineE 2.718281828459045 - #defineEPS 1.0e18 to #definell Long Long + using namespacestd; - the inta[1111],b[4],c[4]; * $ intMain ()Panax Notoginseng { - intN; theCin>>N; + for(intI=0; i<n;i++) A { theCin>>A[i]; +b[a[i]]++; - } $ for(intI=0; i<b[1];i++) $ if(a[i]!=1) -c[1]++; - for(inti=b[1];i<b[2]+b[1];i++) the if(a[i]==3) -c[2]++;Wuyi for(inti=b[1]+b[2];i<n;i++) the if(a[i]==2) -c[3]++; Wucout<<c[1]+max (c[2],c[3]) <<Endl; - return 0; About}
View Code
Sorting a three-valued Sequence (sort of three values)