USCAO Sorting a Three-Valued Sequence

来源:互联网 发布:手表品牌排行榜 知乎 编辑:程序博客网 时间:2024/06/06 09:44
Sorting a Three-Valued Sequence 
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 sortedLines 2-N+1:A single integer from the set {1, 2, 3}

SAMPLE INPUT (file sort3.in)

9221333231

OUTPUT FORMAT

A single line containing the number of exchanges required

SAMPLE OUTPUT (file sort3.out)

4

先用数组录入,再把应该有的序列通过qsort排列出来

一开始没想到有些需要三个轮换

直接记录两个数组差的个数再除2

正确做法是先看哪些可以一次换完(directchange)

再看哪些需要三个互相轮换(两轮交换)(threeexchange)

最后把这两个加起来

代码如下

/*
ID: huangha15
LANG: C
TASK: sort3
*/
#include <stdio.h>
#include <stdlib.h>
int ori[1001],newone[1001];
int cmp(const void *a,const void *b)
{
    const int *x,*y;
    x = a;
    y = b;
    if(*x>*y)
        return 1;
    else
        return -1;
}
int main()
{
   int i,j,n,cur,difference=0,threechange=0,directexchange=0;
   FILE *fin = fopen("sort3.in","r");
   FILE *fout =fopen("sort3.out","w");
   fscanf(fin,"%d",&n);
   for(i=0;i<n;i++)
   {
       fscanf(fin,"%d",&ori[i]);
       newone[i]=ori[i];
   }
   qsort(newone,n,sizeof(newone[0]),cmp);
   for(i=0;i<n;i++)
   {
        for(j=i+1;j<n;j++)
        {
            if(ori[i]!=newone[i]&&ori[j]!=newone[j]&&ori[i]==newone[j]&&newone[i]==ori[j])
            {
                directexchange++;
                cur = ori[j];
                ori[j]=ori[i];
                ori[i]=cur;
            }
        }
   }
     for(i=0;i<n;i++)
     {
         if(ori[i]!=newone[i])
            difference++;
     }
  threechange = difference / 3 * 2;
   fprintf(fout,"%d\n",directexchange+threechange);
   exit(0);
}

0 0