USACO 奶牛排队

题目:给出一个只含有1,2,3的数字序列,问最少交换多少次才能将之变为递增数列。

解:

  注意到只有1,2,3,我们只要将1,3交换到自己的应在位置上那么排序就已经完成了。

  需要交换的有几种,记$a(x,,y)$表示x在应该是y的位置上的$a(i)$的个数,那么我们优先交换a(1,3)和a(3,1)里的数字,一次交换扳正两个位置,接下来要想扳正一个1或3的位置就必须要进行一次交换操作。

  统计计算即可。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 
 6 #define N 1010
 7 
 8 using namespace std;
 9 
10 int n,ans;
11 int cnt[4][4],a[N],b[N];    //cnt(i,j) it should be i,but it's j.
12 
13 int main(){
14     freopen("privc.in","r",stdin);
15     freopen("privc.out","w",stdout);
16     cin>>n;
17     for(int i=1;i<=n;i++) cin>>a[i],b[i]=a[i];
18     sort(b+1,b+n+1);
19     for(int i=1;i<=n;i++) cnt[b[i]][a[i]]++;
20     int t=min(cnt[1][3],cnt[3][1]);
21     ans+=t;
22     ans+=max(cnt[1][3]-t,cnt[3][1]-t);
23     ans+=cnt[1][2];
24     ans+=cnt[3][2];
25     cout<<ans<<endl;
26     fclose(stdin);
27     fclose(stdout);
28     return 0;
29 }
View Code
原文地址:https://www.cnblogs.com/lawyer/p/5701040.html