Dictionary Ordering method
For the arrangement given in the Order of dictionaries (p=p (1) P (2) P (3) p (4) ... p (n)), the algorithm for generating the next permutation from one permutation is as follows:
(1) The maximum value of J to satisfy the relationship p (j-1) <p (j) is set to I, i.e. i=max{j|p (j-1) <p (j)}
(2) To satisfy the relationship of P (i-1) <p (k) The maximum value of K is set to J, that is J=max{k|p (i-1) <p (k)}
(3) P (i-1) and P (j) interchange position, get P ' =p (1) P (2) ... p (n)
(4) in P ' =p (1) P (2) ... p (i-1) p (i) p (i+1) p (n), the P (i) p (i+1) ... p (n) in reverse order, the resulting p=p (1) P (2) ... p (i-1) p (n) p (n-1) ... p (i) sequence is the request. The meaning of J is the subscript of the permutation, for an arrangement with n number, the range of J is from 0 to N. P (j) is the number of the first J of this arrangement.
Attached Source:
Var
P:array[0..1000]of Longint;
I,n,j,k,t:longint;
Begin
READLN (n);
For I:=1 to n do p[i]:=i;
Repeat
For I:=1 to N do write (P[i], "); Writeln;
For J:=1 to N does if p[j-1]<p[j] then i:=j;
For K:=1 to N does if p[i-1]<p[k] then j:=k;
T:=P[I-1]; P[I-1]:=P[J]; p[j]:=t;
For K:=i to (i+n) SHR 1 does
Begin
T:=P[K]; P[k]:=p[n-k+i]; p[n-k+i]:=t;
End
Until I=1;
End.
Algorithm for generating permutations