NextPerm

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
n, i, t, j, k, ind, max, min, o: integer;
a, c, d: array[1..50000] of integer;
procedure quit;
begin
write('IMPOSSIBLE');
halt;
end;
begin
reset(input, 'nextperm.in');
rewrite(output, 'nextperm.out');
read(n);
if n=1 then quit;
for i:= 1 to n do read(a[i]);
for i:= 1 to n-1 do if a[i] <= a[i+1] then break else if i = n-1 then quit;
i:=n;
while a[i] < a[i-1] do begin i:= i - 1;
min:= a[i];
ind:= i;
for j:= i+1 to n do if (a[j] > a[i-1]) and (a[j] < min) then begin
min:=a[j];
ind:=j;
end;
t:=a[ind];
a[ind]:=a[i-1];
a[i-1]:=t;
t:=a[ind];
for j:=i to n do if j<>ind then begin
if a[j]<a[ind] then if j=i+1 then break else begin
for k:=n downto j do begin
a[k]:=a[k-1];
end;
a[j]:=t;
end;
break;
end;
for j:= 1 to i-1 do c[j]:= a[j];
for j:= i to n do c[j]:= a[n-j+i];
for i:= 1 to n do if i <> n then write(c[i], ' ') else write(c[i]);
{ TODO -oUser -cConsole Main : Insert code here }
end.