USACO SECTION 2.1 Sorting a Three-Valued Sequence

本文介绍了一种针对仅有三种不同键值(1、2、3)的特殊排序问题的解决方案,通过交换操作实现非递减排序,并提供了一个具体的C语言程序实例。
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 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

 

/*
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)这样的组合可以看成一个环,需要交换两次

其他都只要交换一次就可以

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值