Sorting A Three-Valued Sequence

来源:互联网 发布:国家工商行政网络 编辑:程序博客网 时间:2024/06/14 13:16

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
题目意思:
求将给你的这个数组排成有序至少需要交换多少个元素
自己虽然做出来了,但是那个思路恶心了,看analysis的那个超级棒,所 以忍不住翻译记载一下
We read the input into an array, and sort a copy of it in another array, so we know what we have and what we want. 

A swap touches two elements, so it can correct at most two misplaced elements. We run through the array looking for pairs of misplaced elements that a swap would correct, and do those swaps.

The remaining misplaced elements form little cycles: a 1 where a 2 should be, a 2 where a 3 should be, and that 3 where the 1 should be. It takes two swaps to correct such a cycle. So we count the number of such cycles (by counting misplaced elements and dividing by three) and then add in two times that many swaps.

 

我们读输入数据到一个数组,然后用另一个数组复制它并排序,因此我们得以知道这个数组现在的样子跟排好的样子。

一个交换涉及到两个元素,所以它最多能纠正两个错放的元素。我们浏览数组查找一次交换就能纠正的错放的元素对跟交换他们。

剩下的错放的元素组成了小循环:2放在1那,3放在2那,然后1放在3那。需要两次交换才能修正这样一个循环。
所以我们记下这样的循环的数量(通过统计错放的元素然后将他除以3),最后加两次这样的循环的数量

 

 
原创粉丝点击