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;
}