A permutation P=(p1,p2,…,pn) uses each integer from 1 to n exactly once. List every permutation of length n in lexicographic order and let d(P) be the position of P in that list. The first one, (1,2,…,n), has number 1.
Write a program that computes d(P) without generating all permutations of length n. Here n is at most 50.
For n=4, the permutations in lexicographic order and their numbers are shown below.

If P=(2,3,4,1) then d(P)=10, and if P=(4,2,1,3) then d(P)=21.
The input has several lines. Each line holds one query in the form (n,(p1,p2,…,pn)) and contains no spaces. The last line holds only −1, and the input ends there. At least one query is given.
Print d(P) for every query on a single line, in the order the queries are given. Separate two values with one comma, and put no space before or after the comma.