AmazingCounters.com

USACO Sorting a Three-Valued Sequence

 

题目大意:给你一个只有1 2 3 的序列,要你排序,每次可以交换任意两个元素,问最小交换次数是多少

思路:贪心,先排1 ,如果1已经在位置上了,那就不要动了,如果是2那就和最前面的1交换,如果是3,那就和后面的1交换

 

 

 1 /*{
 2 ID:a4298442
 3 PROB:sort3
 4 LANG:C++
 5 }
 6 */
 7 #include<iostream>
 8 #include<fstream>
 9 #define maxn 5000
10 using namespace std;
11 ifstream fin("sort3.in");
12 ofstream fout("sort3.out");
13 //#define fin cin
14 //#define fout cout
15 int a[maxn],listone[maxn];
16 int main()
17 {
18     int n,one=0,two=0,three=0,h=0,r=0,l=0,ans=0;
19     fin>>n;
20     for(int i=1;i<=n;i++)
21     {
22         fin>>a[i];
23         if(a[i]==1)one++,listone[++r]=i;
24         if(a[i]==2)two++;
25         if(a[i]==3)three++;
26     }
27     for(int i=1;i<=one;i++)if(a[i]==1)l++;
28     for(int i=1;i<=one;i++)
29     {
30         if(a[i]==1)continue;
31         else if(a[i]==2)
32         {
33             swap(a[i],a[listone[++l]]);
34             ans++;
35         }
36         else if(a[i]==3)
37         {
38             swap(a[i],a[listone[r--]]);
39             ans++;
40         }
41     }
42     for(int i=one+1;i<=one+two;i++)
43     {
44         if(a[i]==3)ans++;
45     }
46     fout<<ans<<endl;
47     return 0;
48 }

 

posted @ 2015-03-07 13:23  philippica  阅读(132)  评论(0编辑  收藏  举报