一.题目描述
Sorting is one of the most frequently performed computational tasks. Consider the special sorting problem in which the records to be sorted have at most three different key values. This happens for instance when we sort medalists of a competition according to medal value, that is, gold medalists come first, followed by silver, and bronze medalists come last.
In this task the possible key values are the integers 1, 2 and 3. The required sorting order is non-decreasing. However, sorting has to be accomplished by a sequence of exchange operations. An exchange operation, defined by two position numbers p and q, exchanges the elements in positions p and q.
You are given a sequence of key values. Write a program that computes the minimal number of exchange operations that are necessary to make the sequence sorted.
PROGRAM NAME: sort3
INPUT FORMAT
Line 1: N (1 <= N <= 1000), the number of records to be sorted
Lines 2-N+1: A single integer from the set {1, 2, 3}
SAMPLE INPUT (file sort3.in)
9
2
2
1
3
3
3
2
3
1
OUTPUT FORMAT
A single line containing the number of exchanges required
SAMPLE OUTPUT (file sort3.out)
4
二.题目分析
本题中采用最小交换策略即可,原始的数组为prime,正确排序的数组为right,对于每一个i,若prime[i]=right[i],则不需要交换;若prime[i]!=right[i],则需要交换,为使交换次数最少,我们当然希望找到正好相反的序对,如prime[i]=1,right[i]=3,则我们希望找到prime[i]=3,right[i]=1,这样一次交换即可成功,但是现实并不总是这么美好,除去这些一次交换成功的序对之外,还存在这种情况,prime[i]=1,right[i]=3 prime[j]=2,right[j]=1 prime[k]=3,right[k]=2,这种三错乱序对,对于这种情况,则只需交换两次即可成功。以上分析就是所有的错乱情况和最少交换情况,可得如下代码.
三.代码
#include <stdio.h>
#include <stdlib.h>
#define MAX 1001
int cmp(const void*a,const void*b)
{
return (*(int *)a)-(*(int *)b);
}
int main()
{
int num[MAX],temp[MAX],kind[4][4],N,i,j,k1,k2;
FILE *in=fopen("sort3.in","r"),*out=fopen("sort3.out","w");
if(!in||!out)
{
printf("file open error!\n");
return -1;
}
fscanf(in,"%d",&N);
for(i=0;i<N;i++)
{
fscanf(in,"%d",&num[i]);
temp[i]=num[i];
}
//temp中保存的正确的顺序数组
qsort(temp,N,sizeof(int),cmp);
for(i=1;i<=3;i++)
for(j=1;j<=3;j++)
kind[i][j]=0;
//记录正确和错位的情况,i=j时为正确的,不需要交换,i!=j时是错误的,需要交换,可交换一次或者两次
for(i=0;i<N;i++)
kind[temp[i]][num[i]]++;
//k1中保存两组数可以直接交换即成功的个数(交换一次)
k1=0;
k1+=(kind[1][2]<kind[2][1]?kind[1][2]:kind[2][1]);
k1+=(kind[1][3]<kind[3][1]?kind[1][3]:kind[3][1]);
k1+=(kind[2][3]<kind[3][2]?kind[2][3]:kind[3][2]);
//k1中保存三组数相互交换成功的个数(交换两次)
if((kind[1][2]-kind[2][1])>0)
k2=kind[1][2]-kind[2][1];
else
k2=kind[2][1]-kind[1][2];
fprintf(out,"%d\n",k1+k2*2);
return 0;
}