[USACO 2.1.3]三值的排序

地址:http://hustoj.sinaapp.com/problem.php?id=1839

将乱序的数列中的元素两两交换,变成升序数列,输出所需最小步骤数

其实就是模拟一个过程,只有三种数,先是找只需交换一次便归位的,然后是交换两次三个数归位的,交换时计数就行

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 
 5 using namespace std;
 6 vector<int> num,con(4);
 7 int n,con_num;
 8 
 9 void swap(int& a,int& b)
10 {
11     int t;
12     t=a;
13     a=b;
14     b=t;
15 }
16 
17 bool there(int& a,int& b)
18 {
19     if(a>=con[num[b]-1] && a<con[num[b]]) return true;
20     else return false;
21 }
22 
23 int main()
24 {
25     ios::sync_with_stdio(false);
26     cin>>n;
27     for(int i=0;i<n;i++)
28     {
29         int t;
30         cin>>t;
31         num.push_back(t);
32         con[t]++;
33     }
34     con[2]+=con[1];
35     con[3]+=con[2];
36     for(int i=0;i<n;i++)
37     {
38         if(!there(i,i))
39         {
40             for(int j=con[num[i]-1];j<con[num[i]];j++)
41             {
42                 if(there(i,j))
43                 {
44                     swap(num[i],num[j]);
45                     con_num++;
46                     break;
47                 }
48             }
49         }
50     }
51     for(int i=0;i<n;i++)
52     {
53         if(there(i,i)) continue;
54         for(int j=i+1;j<n;j++)
55         {
56             if(there(j,j)) continue;
57             if(there(i,j))
58             {
59                 swap(num[i],num[j]);
60                 con_num++;
61                 break;
62             }
63         }
64     }
65     cout<<con_num<<endl;
66     return 0;
67 }

 

posted @ 2013-03-09 19:08  tjsuhst  阅读(320)  评论(0编辑  收藏  举报