IOI'96 - Day 2
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 requiredSAMPLE OUTPUT (file sort3.out)
4
/*
ID: conicoc1
LANG: C
TASK: sort3
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int comp(const void *a,const void *b)
{
return *(int*)a-*(int*)b;
}
int Min(int a,int b)
{
if(a<b)
return a;
return b;
}
int main()
{
FILE *fin,*fout;
fin=fopen("sort3.in","r");
fout=fopen("sort3.out","w");
int A[1000],B[1000];
int N,i;
int count;
int temp[4][4];
fscanf(fin,"%d",&N);
memset(temp,0,sizeof(temp));
for(i=0;i<N;i++)
{
fscanf(fin,"%d",&A[i]);
B[i]=A[i];
}
qsort(A,N,sizeof(int),comp); //A已排序
for(i=0;i<N;i++)
{
temp[A[i]][B[i]]++;
}
count=fabs(temp[1][2]-temp[2][1])*2+Min(temp[1][2],temp[2][1])+Min(temp[1][3],temp[3][1])+Min(temp[2][3],temp[3][2]);
fprintf(fout,"%d\n",count);
return 0;
}
记得数据结构的书上有讲过这个类型
找到有多少组前面比后面大的情况
(2,1) (3,1)(3,2)
好像当时是在分析时间复杂度的问题,一会儿去翻一下看看
出现
(2,3,1)这样的组合可以看成一个环,需要交换两次
其他都只要交换一次就可以