Kanto expansion (used for Full Permutation and Integer Conversion)

Source: Internet
Author: User
Kanto expansion formula

X = An * (n-1 )! + An-1 * (n-2 )! +... + AI * (I-1 )! +... + A2 * 1! + A1 * 0! Where, A is an integer and 0 <= AI <I (1 <= I <= N ). This is Kanto.

Expand instance {1, 2, 3, 4 ,..., n} indicates 1, 2, 3 ,..., for example, {1, 2, 3} is arranged in ascending order of N. 123 132 213 231 312 321.

The number 1, 2, 4, 5, and 6 correspond to a given number.

The relationships between them can be found in Kanto.

If you want to know the number of the largest numbers in 321 is {1, 2, 3}, you can consider this as follows:

The first digit is 3. When the first digit is less than 3, the number is smaller than 321, for example, 123 and 213. The number smaller than 3 is 1 and 2. So there are 2*2! . Let's look at the number smaller than the second digit 2: only one number smaller than 2 is 1, so there is 1*1! = 1 so the number of {1, 2, 3} arrays smaller than 321 is 2*2! + 1*1! = 5. So 321 is a large number of 6th. 2*2! + 1*1! + 1*0! Is to expand the Kanto.

For another example, 1324 is the largest number in the {1, 2, 3, 4} number. The first is the number where 1 is smaller than 1. The number is 0 0*3! The second digit is 3 less than 3. The numbers are 1 and 2, but 1 is already in the first place, so there is only one digit 2 1*2! . The third digit is 2 and the number smaller than 2 is 1, but 1 is in the first place, so there are 0 numbers 0*1! So there are 0*3 smaller than 1324! + 1*2! + 0*1! = 2, 1324 is the third large number. Code

const int PermSize = 12;long long factory[PermSize] = { 0, 1, 2, 6, 24, 120,720, 5040, 40320, 362880, 3628800,39916800 };long long Cantor(string buf) {int i, j, counted;long long result = 0;for (i = 0; i < PermSize; ++i) {counted = 0;for(j = i + 1; j < PermSize; ++j)if(buf[i] > buf[j])++counted;result = result + counted *factory[PermSize - i - 1];}return result;}

Source: Baidu encyclopedia

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.