
задается N и сама пермутация длины N. требуеться найти индекс этой пермутации в N!
пример:
4
2 3 1 4
ответ: 17
пример:
5
5 4 3 2 1
ответ: 120
и т.д
помогите пожалуйста с реализацией алгоритма...

спс за внимание(заранее)

function Fact(n: integer): longint;
var
i: integer;
T: longint;
begin
T := 1;
for i := 1 to n do T := T * i;
Fact := T;
end;
function PermutationNum(const A : array of integer; N : Integer): longint;
var
T, i, j: integer;
F: longint;
theResult: longint;
begin
if N <= 0 then begin
PermutationNum := 0; Exit;
end;
I:=1;
while I <= N do begin
if (A[I]<1) or (A[I]>N) then begin
PermutationNum := 0; Exit;
end;
Inc(I);
end;
theResult := 0;
F := 1;
I := 1;
while I <= N do begin
F := F*I;
Inc(I);
end;
I := 1;
while I <= N-1 do begin
F := F div (N+1-I);
T := A[I]-1;
J := 1;
while J <= I-1 do begin
if A[J]<A[I] then begin
T := T-1;
end;
Inc(J);
end;
theResult := theResult + F*T;
Inc(I);
end;
theResult := theResult + 1;
PermutationNum := theResult;
end;
const
n: integer = 3;
var
arr: array[0 .. 8] of integer;
s: string;
i: integer;
p, total: longint;
begin
write('n = '); readln(n);
write('number[', n, ' chars] = '); readln(s);
arr[0] := 0;
for i := 1 to n do arr[i] := ord(s[i]) - ord('0');
p := PermutationNum(arr, n);
total := Fact(n);
writeln(total - p);
end.