您的位置:首页 > 其它

【计蒜客系列】挑战难题27:三值排序

2015-08-06 16:43 489 查看
题目来源:计蒜客

排序是一种很频繁的计算任务。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌排序的时候。在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。

写一个程序计算出,计算出的一个包括1、2、3三种值的数字序列,排成升序所需的最少交换次数。

输入第1行为类别的数量N(1≤N≤1000)

输入第2行到第N+1行,每行包括一个数字(1或2或3)。

输出包含一行,为排成升序所需的最少交换次数。

样例1

输入:

9

2

2

1

3

3

3

2

3

1

输出:
4

注:此题使用贪心方法。(参考资料

<pre name="code" class="cpp">#include<stdio.h>

int a[1001];
int count[4];//交换次数
int num1, num2, num3, n ,ans = 0;
// num1表示位置为1的地方非1的个数;num2表示位置为2的地方3的个数;num3表示位置为3的地方2的个数;
// ans = x + max(y,z)
int main() {

scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
++count[a[i]];
}

for (int i = 1; i <= count[1]; ++i)
if (a[i] != 1)
++num1;
for (int i = count[1] + 1; i <= count[1] + count[2]; ++i)
if (a[i] == 3)
++num2;
for (int i = count[1] + count[2] + 1; i <= n; ++i)
if (a[i] == 2)
++num3;
int max = 99999;
if (num2 > num3)
max = num2;
else
max = num3;
ans = num1 + max;
printf("%d\n", ans);
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: