#include <algorithm>
#include <cassert>
#include <numeric>
using namespace std;
typedef int Num;
int const MAX_N = 11;
Num fact [MAX_N + 1];
/// precompute factorials
void prepare (int limit)
{
fact[0] = 1;
for (int i = 1; i <= limit; i++)
{
fact[i] = fact[i - 1] * i;
}
}
/// parameters: permutation perm of 0, 1, ..., len-1, and its length len
/// result: lexicographical number of permutation
Num perm_to_num (int * perm, int len)
{
int mask = (1 << len) - 1;
Num res = 0;
for (int pos = 0; pos < len; pos++)
{
int bit = 1 << perm[pos];
int add = __builtin_popcount (mask & (bit - 1));
res += add * fact[len - pos - 1];
mask ^= bit;
}
assert (mask == 0);
return res;
}
int main (void)
{
prepare (MAX_N);
int const len = MAX_N;
// testing: all permutations of length len
int perm [len];
iota (perm, perm + len, 0);
Num num_check = 0;
do
{
Num num = perm_to_num (perm, len);
assert (num == num_check);
num_check += 1;
}
while (next_permutation (perm, perm + len));
return 0;
}
I2luY2x1ZGUgPGFsZ29yaXRobT4KI2luY2x1ZGUgPGNhc3NlcnQ+CiNpbmNsdWRlIDxudW1lcmljPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnR5cGVkZWYgaW50IE51bTsKCmludCBjb25zdCBNQVhfTiA9IDExOwoKTnVtIGZhY3QgW01BWF9OICsgMV07CgovLy8gcHJlY29tcHV0ZSBmYWN0b3JpYWxzCnZvaWQgcHJlcGFyZSAoaW50IGxpbWl0KQp7CglmYWN0WzBdID0gMTsKCWZvciAoaW50IGkgPSAxOyBpIDw9IGxpbWl0OyBpKyspCgl7CgkJZmFjdFtpXSA9IGZhY3RbaSAtIDFdICogaTsKCX0KfQoKLy8vIHBhcmFtZXRlcnM6IHBlcm11dGF0aW9uIHBlcm0gb2YgMCwgMSwgLi4uLCBsZW4tMSwgYW5kIGl0cyBsZW5ndGggbGVuCi8vLyByZXN1bHQ6IGxleGljb2dyYXBoaWNhbCBudW1iZXIgb2YgcGVybXV0YXRpb24KTnVtIHBlcm1fdG9fbnVtIChpbnQgKiBwZXJtLC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