这道题需要涉及到置换群的知识,只需知道一个定理。
最小交换次数=元素个数-环的个数。
View Code
1 program pku1674(input,output); 2 var 3 number :array[0..11000] of integer; 4 v :array[0..11000] of boolean; 5 n,cases:longint; 6 answer :longint; 7 procedure init; 8 var 9 i:longint;10 begin11 readln(n);12 for i:=1 to n do13 read(number[i]);14 fillchar(v,sizeof(v),false);15 end;{ init }16 procedure main;17 var18 now,i:longint;19 begin20 answer:=0;21 for i:=1 to n do22 if not v[i] then23 begin24 inc(answer);25 v[i]:=true;26 now:=number[i];27 while not v[now] do28 begin29 v[now]:=true;30 now:=number[now];31 end;32 end;33 end;{ main }34 procedure print;35 begin36 writeln(n-answer);37 end;{ print }38 begin39 readln(cases);40 while cases>0 do41 begin42 dec(cases);43 init;44 main;45 print;46 end;47 end.