2.1.3---Sorting a Three-Valued Sequence

Sorting is one of the most frequently performed computational tasks. Consider the special sorting problem in which the records to be sorted have at mostthree 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
      三值的排序
  IOI'96 - Day 2 
  
  译 by !Starliu
  
  排序是一种很频繁的计算任务。现在考虑最多只有三值的排序问题。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌序的时候。
  
  在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。
  
  写一个程序计算出,给定的一个1,2,3组成的数字序列,排成升序所需的最少交换次数。
/*
ID:******
PROG:sort3
LANG:C++
*/
#include <iostream>
#include <fstream>
using namespace std;

int n;//问题规模
int st[1001];//储存原始数据

int main(){
	ofstream fout ("sort3.out");
	ifstream fin ("sort3.in");
	int num_1,num_2,num_3;//分别记录数字等于1,2,3的分区大小
	int count;//记录结果规模

	//输入数据
	fin >> n;
	for (int i = 0;i < n; i ++)
		fin >> st[i];

	//按数字数量分区
	num_1 = num_2 = num_3 = 0;
	for (int i = 0;i < n;i ++){
		if(st[i] == 1)
			num_1 ++;
		else{
			if(st[i] == 2)
				num_2 ++;
			else
				num_3 ++;
		}
	}

	//开始搜索
	count = 0;
	for (int i = 0; i < num_1; i ++){//遍历1区
		if(st[i] == 2)//若等于2则由此向后搜索1
			for(int j = num_1;j < n;j ++){
				if(st[j] == 1){//如果找到1,则交换
					st[j] = st[i];
					st[i] = 1;
					count ++;
					break;
				}
			}
		if(st[i] == 3)//若等于3则由后到此搜索1
			for(int j = n - 1;j >= num_1;j --){
				if(st[j] == 1){//如果找到1,则交换
					st[j] = st[i];
					st[i] = 1;
					count ++;
					break;
				}
			}
	}
	for (int i = num_1; i < num_1 + num_2; i ++){//遍历2区
		if(st[i] != 2)//若不等于2则向后搜索2
			for(int j = num_1+num_2; j < n; j ++){
				if(st[j] == 2){//如果找到2,则交换
					st[j] = st[i];
					st[i] = 2;
					count ++;
					break;
				}
			}
	}
	fout << count <<endl;
	return 0;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值