pku1674 Sorting by Swapping
这道题需要涉及到置换群的知识,只需知道一个定理。
最小交换次数=元素个数-环的个数。
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 begin 11 readln(n); 12 for i:=1 to n do 13 read(number[i]); 14 fillchar(v,sizeof(v),false); 15 end;{ init } 16 procedure main; 17 var 18 now,i:longint; 19 begin 20 answer:=0; 21 for i:=1 to n do 22 if not v[i] then 23 begin 24 inc(answer); 25 v[i]:=true; 26 now:=number[i]; 27 while not v[now] do 28 begin 29 v[now]:=true; 30 now:=number[now]; 31 end; 32 end; 33 end;{ main } 34 procedure print; 35 begin 36 writeln(n-answer); 37 end;{ print } 38 begin 39 readln(cases); 40 while cases>0 do 41 begin 42 dec(cases); 43 init; 44 main; 45 print; 46 end; 47 end.