现在有"abcdefghijkl”12个字符,将其所有的排列中按字典序排列,给出任意一种排列,说出这个排列在所有的排列中是第几小的?
3 abcdefghijkl hgebkflacdji gfkedhjblcia
1 302715242 260726926
康托展开:
#include <stdio.h> #include <string.h> int findLess(char str[]){ int i, count = 0; for(i = 1; str[i] != '\0'; ++i) if(str[i] < str[0]) ++count; return count; } int jieCheng(int n){ if(n == 1) return 1; return n * jieCheng(n - 1); } int main(){ char str[13]; int t, a[13], sum; scanf("%d", &t); while(t--){ scanf("%s", str); memset(a, 0, sizeof(a)); for(int i = 0; i < 12; ++i) a[11 - i] = findLess(str + i); sum = 0; for(int i = 0; i < 12; ++i) if(a[i]) sum += a[i] * jieCheng(i); printf("%d\n", sum + 1); } return 0; }