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.
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}
9 2 2 1 3 3 3 2 3 1
4
排序是一种很频繁的计算任务。现在考虑最多只有三值的排序问题。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌序的时候。在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。
写一个程序计算出,给定的一个1,2,3组成的数字序列,排成升序所需的最少交换次数。
PROGRAM NAME: sort3
INPUT FORMAT:
(file sort3.in)
Line 1:
N (1 <= N <= 1000)
Lines 2-N+1:
每行一个数字,共N行。(1..3)
OUTPUT FORMAT:
(file sort3.out)
共一行,一个数字。表示排成升序所需的最少交换次数。
9 2 2 1 3 3 3 2 3 1
4
这题,真是想复杂了。。。
我以为是给任意三个数然后排序呢,
没想到是只有1,2,3三个数。。。
真是要命啊。。。
然后理解题意后我们可以这样想,
记录a[1,2],a[1,3],a[2,1],a[2,3],a[3,1],a[3,2]
分别为本该1的位置2占了几个,3占了几个。。。。后四个意义同上
对于a[x,y]和a[y,x],取较小值加到总操作数中,
代表对应的x,y的错位进行交换
两两交换后就只剩下三个三个错位的了,
最后不用枚举直接加上
(a[1,2]+a[1,3])*2就行了,
即a[1,2]*2+a[1,3]*2
就是同时换三个值,每换一次要执行两次操作,最终的操作数直接输出就可以了
{ ID: codeway3 PROG: sort3 LANG: PASCAL } program sort3; var i,j,k,l,n,m:longint; a,b,c:longint; x:array[1..3,1..3]of longint; y:array[1..1000]of longint; z:array[1..3]of longint; function min(xx,yy:longint):longint; begin if xx<yy then exit(xx); exit(yy); end; begin assign(input,'sort3.in'); reset(input); assign(output,'sort3.out'); rewrite(output); readln(n); for i:=1 to n do begin read(y[i]); inc(z[y[i]]); end; for i:=1 to z[1] do inc(x[1,y[i]]); for i:=z[1]+1 to z[1]+z[2] do inc(x[2,y[i]]); for i:=z[1]+z[2]+1 to z[1]+z[2]+z[3] do inc(x[3,y[i]]); j:=min(x[1,2],x[2,1]); m:=m+j; x[1,2]:=x[1,2]-j; x[2,1]:=x[2,1]-j; j:=min(x[1,3],x[3,1]); m:=m+j; x[1,3]:=x[1,3]-j; x[3,1]:=x[3,1]-j; j:=min(x[2,3],x[3,2]); m:=m+j; x[2,3]:=x[2,3]-j; x[3,2]:=x[3,2]-j; m:=m+(x[1,2]+x[1,3])*2; writeln(m); close(input); close(output); end.