Description
排序是一种很频繁的计算任务。现在考虑最多只有三值的排序问题。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌序的时候。
在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。
写一个程序计算出,给定的一个1,2,3组成的数字序列,排成升序所需的最少交换次数。
Input
Line 1:
N (1 <= N <= 1000)
Lines 2-N+1:
每行一个数字,共N行。(1..3)
Output
共一行,一个数字。表示排成升序所需的最少交换次数。
末尾有空行
题解
This question is too water!
Executing…
Test 1: TEST OK [0.000 secs, 348 KB]
Test 2: TEST OK [0.000 secs, 348 KB]
Test 3: TEST OK [0.000 secs, 348 KB]
Test 4: TEST OK [0.000 secs, 348 KB]
Test 5: TEST OK [0.000 secs, 348 KB]
Test 6: TEST OK [0.000 secs, 348 KB]
Test 7: TEST OK [0.000 secs, 348 KB]
Test 8: TEST OK [0.000 secs, 348 KB]
All tests OK.
代码
{
ID: zyx52yzl
LANG: PASCAL
TASK: sort3
}
var
n,tk,ans:longint;
a,b:array [0..1001] of longint;
num:array [1..3,1..3] of longint;
procedure init;
var
i:longint;
begin
readln(n);
for i:=1 to n do
begin
read(a[i]);
b[i]:=a[i];
end;
end;
procedure qsort(l,r:longint);
var
i,j,mid,t:longint;
begin
if l>r then exit;
i:=l; j:=r;
mid:=b[(i+j) div 2];
repeat
while b[i]<mid do inc(i);
while b[j]>mid do dec(j);
if i<=j then
begin
t:=b[i]; b[i]:=b[j]; b[j]:=t;
inc(i); dec(j);
end;
until i>j;
qsort(l,j);
qsort(i,r);
end;
function min(o,p:longint):longint;
begin
if o<p then exit(o);
exit(p);
end;
procedure main;
var
i:longint;
begin
for i:=1 to n do
if b[i]<>a[i] then
begin
inc(num[b[i],a[i]]);
inc(tk);
end;
ans:=ans+min(num[1][2],num[2][1]);
tk:=tk-min(num[1][2],num[2][1])*2;
ans:=ans+min(num[1][3],num[3][1]);
tk:=tk-min(num[1][3],num[3][1])*2;
ans:=ans+min(num[3][2],num[2][3]);
tk:=tk-min(num[3][2],num[2][3])*2;
end;
begin
assign(input,'sort3.in');
assign(output,'sort3.out');
reset(input);
rewrite(output);
init;
qsort(1,n);
main;
writeln(ans+(tk div 3)*2);
close(input);
close(output);
end.