USACO2.13 sort3

题意:给定一个长度为N的数组,全部由{1,2, 3}组成,求将其排列成不降序列的最少移动次数

分析:求出每个1,2,3 各自 是数量,count[1],count[2],count[3]; 这样也就知道了排列后各个元素所属的区域;

接下来,我们先需要考虑1 和2 俩块区域;

交换一次,能够回到自己所属的区域,应该就是最好的交换了,这样我们就优先考虑交换之后俩俩可以回到自己位置的交换

 for (int i=1;i<=count[1]+count[2];i++){
        if (t[i]==3) a[3]++;
        else if (t[i]==2&&i<=count[1]) a[1]++;
        else if (t[i]==1&&i>count[1]) a[2]++;
        }

从上面的代码来说吧,取a[1] 与a[2]中较小的一个,我们会发现t= min(a[1],a[2]) 值就是1 和2 直接交换的次数,t次交换后的结果就是有t个1和t个2回到了各自所属的区域上;接下来,1和2区域中的3 肯定要与下面的3区域交换,进行a[3]次交换(当然是尽量选择可以让自己回到所属区域的交换,但总次数仍然是a[3]次)之后,3全部回到所属区域,自己先一个数据就会发现,这时候若1区域还有2区域中仍有错位的数字,那是因为a[1] 和a[2]不相等,还需要交换的次数为abs(a[1]-a[2]);

最后,最小的交换次数则为 a[3] + max(a[1],a[2])

/*
ID: nanke691
LANG: C++
TASK: sort3
*/
#include<fstream>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main()
{
    freopen("sort3.in","r",stdin);
    freopen("sort3.out","w",stdout);
    int count[4],a[4],t[1001],x,n,k=0;
    memset(count,0,sizeof(count));
    memset(a,0,sizeof(a));
    scanf("%d",&n);
    while (n--) {
		scanf("%d",&x);
          count[x]++;
          t[++k]=x;
          }
    for (int i=1;i<=count[1]+count[2];i++){
        if (t[i]==3) a[3]++;
        else if (t[i]==2&&i<=count[1]) a[1]++;
        else if (t[i]==1&&i>count[1]) a[2]++;
        }
    cout<<a[3]+max(a[1],a[2])<<endl;
}
原文地址:https://www.cnblogs.com/nanke/p/2221578.html