Sorting a Three-Valued Sequence 三值的排序

Description

排序是一种很频繁的计算任务。现在考虑最多只有三值的排序问题。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌序的时候。 在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。 写一个程序计算出,给定的一个1,2,3组成的数字序列,排成升序所需的最少交换次数。

Input

Line 1: N (1 <= N <= 1000) Lines 2-N+1: 每行一个数字,共N行。(1..3)

Output

共一行,一个数字。表示排成升序所需的最少交换次数。

Sample Input

9
2
2
1
3
3
3
2
3
1

Sample Output

4

题解:

分别计算出1、2、3的个数,在原数组中分成这样长度的三段,把第二段第三段中的 1 换到第一段,然后再把第二段跟第三段中位置不对的数换过去。

代码如下:

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#define MAX 0x3f3f3f3f
using namespace std;
typedef long long LL;
int main()
{
    int n,a[1111],b[5][5],y=0,e=0,s=0;
    cin >> n;
    memset(b,0,sizeof(b));
    for(int i=1; i<=n; i++)
    {
        cin >> a[i];
        if(a[i]==1)
            y++;
        else if(a[i]==2)
            e++;
        else
            s++;
    }
    for(int i=1; i<=n; i++)
    {
        if(i>=1&&i<=y)
            b[1][a[i]]++;
        else if(i>y&&i<=e+y)
            b[2][a[i]]++;
        else
            b[3][a[i]]++;
    }
    int sum=0;
    sum+=b[2][1];
    if(b[1][2]>=b[2][1])
        b[1][2]-=b[2][1];
    else
        b[2][3]+=b[2][1]-b[1][2];
    sum+=b[3][1]+b[2][3];
    cout <<sum <<endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值