Hi!

Your brute force algorithms obviously cant pass the online judge because in the worst case it has to make as much as 2^30 procedure calls .

Note, that permutation number is just number of permutations which are lesser than given one (+1). So you just have to count all permutations which are lesser than given.

Permutation a is lesser than permutation b if one of the following is true:

1. a[0] < b[0]

or

2. a[0]==b[0] && a[1..N] < b[1..N]

Number of permutations of first type is easy to calculate

you should just iterate over all characters which are smaller than s[0] and check the number of ways to order the remaining string characters.

For example, for string "cdaab"

number of permutations of first type is

number of permutations starting from a ( remaining characters are 1 'a', 1'b', 1'c', 1'd'

it gives us 4! perms)

+ number of permutations starting from b (remaining characters are 2 'a', 1'c', 1'd'

it gives us 4!/2! perms NOTE THE DUPLICATE 'a' character)

So we have 4! + (1/2)*4! = 36 permutations of first type

To get the number of permutations of second type we can just remove the first character and call ourself recursively (i.e. for string "daab")

So, full calculations for string "cdaab" are as follows:

-- doit called for "cdaab"

+ 1. Number of perms in the following set { d, b, c, a } = 24

+ 2. Number of perms in the following set { d, c, a, a } = 12

-- doit called for "daab"

+ 3. Number of perms in the following set { a, b, d } = 6

+ 4. Number of perms in the following set { a, a, d } = 3

-- doit called for "aab"

-- doit called for "ab"

-- doit called for "b" and returns 0

So, counting together we get 24+12+6+3 (+1 because answers are numbered

starting from 1) == 46

Final hint:

Number of perms in set with x1 character 'a', x2 characters 'b' ...

xi characters ? is equal to the n! / (x1! * x2! * ... * xi!) where n=x1+...+xi.

Be careful calculating this number because you can easily get overflow even using

long long types.

Note, that 30!/(15!*15!) fits to long long BUT 30! DONT

so calculating n! first and then dividing it by each of the smaller factorials will give you wrong result.

There are a lot of ways to optimize this algorithm, but even this solution is fast enough to pass online judge within several milliseconds.