2.1.3 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的区间内有多少非1 的个数,然后统计2~3区间内3的个数,在统计3~n区间内2的个数,然后我们可以考虑的是非1的个数肯定要去交换位置,后面的话就可以等价替换掉,然后我们就可以考虑计算后两个区间内的最大值,然后相加得出。

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
typedef long long LL;
const long long INF = 0x3f3f3f3f;
const long long mod = 1e9+7;
const double PI = acos(-1.0);
const int maxx = 800;
#define MAX 10010
using namespace std;
int x[1100],y[1100],num1,num2,num3;
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>x[i];
        if(x[i]==1)
            num1++;
        if(x[i]==2)
            num2++;
        if(x[i]==3)
            num3++;
    }
    for(int i=0;i<num1;i++)
        if(x[i]!=1)
            y[1]++;
    for(int i=num1;i<num1+num2;i++)
        if(x[i]==3)
            y[2]++;
    for(int i=num1+num2;i<n;i++)
        if(x[i]==2)
            y[3]++;
    cout<<y[3]+max(y[1],y[2])<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38984851/article/details/82668271
今日推荐