The main idea: to give you a 1 2 3 sequence, you can sort, to exchange any two elements at a time, ask the minimum number of exchanges
Idea: Greedy, first row 1, if 1 is already in position, then do not move, if it is 2 that and the front of the 1 exchange, if 3, then and the back of the 1 exchange
1 /*{2 id:a42984423 Prob:sort34 lang:c++5 }6 */7#include <iostream>8#include <fstream>9 #defineMAXN 5000Ten using namespacestd; OneIfstream Fin ("sort3.in"); AOfstream Fout ("Sort3.out"); - //#define FIN CIN - //#define Fout cout the intA[MAXN],LISTONE[MAXN]; - intMain () - { - intN,one=0, two=0, three=0, h=0, r=0, l=0, ans=0; +Fin>>N; - for(intI=1; i<=n;i++) + { AFin>>A[i]; at if(a[i]==1) one++,listone[++r]=i; - if(a[i]==2) two++; - if(a[i]==3) three++; - } - for(intI=1; i<=one;i++)if(a[i]==1) l++; - for(intI=1; i<=one;i++) in { - if(a[i]==1)Continue; to Else if(a[i]==2) + { -Swap (a[i],a[listone[++L]]); theans++; * } $ Else if(a[i]==3)Panax Notoginseng { -Swap (a[i],a[listone[r--]]); theans++; + } A } the for(intI=one+1; i<=one+two;i++) + { - if(a[i]==3) ans++; $ } $fout<<ans<<Endl; - return 0; -}
Usaco sorting a three-valued Sequence