Finding the ranking of a word (permutations) with duplicate letters

前端 未结 6 616
有刺的猬
有刺的猬 2020-11-27 07:09

I\'m posting this although much has already been posted about this question. I didn\'t want to post as an answer since it\'s not working. The answer to this post (Finding th

6条回答
  •  遥遥无期
    2020-11-27 07:44

    If there are k distinct characters, the i^th character repeated n_i times, then the total number of permutations is given by

                (n_1 + n_2 + ..+ n_k)!
    ------------------------------------------------ 
                  n_1! n_2! ... n_k!
    

    which is the multinomial coefficient.
    Now we can use this to compute the rank of a given permutation as follows:

    Consider the first character(leftmost). say it was the r^th one in the sorted order of characters.

    Now if you replace the first character by any of the 1,2,3,..,(r-1)^th character and consider all possible permutations, each of these permutations will precede the given permutation. The total number can be computed using the above formula.

    Once you compute the number for the first character, fix the first character, and repeat the same with the second character and so on.

    Here's the C++ implementation to your question

    #include
    
    using namespace std;
    
    int fact(int f) {
        if (f == 0) return 1;
        if (f <= 2) return f;
        return (f * fact(f - 1));
    }
    int solve(string s,int n) {
        int ans = 1;
        int arr[26] = {0};
        int len = n - 1;
        for (int i = 0; i < n; i++) {
            s[i] = toupper(s[i]);
            arr[s[i] - 'A']++;
        }
        for(int i = 0; i < n; i++) {
            int temp = 0;
            int x = 1;
            char c = s[i];
            for(int j = 0; j < c - 'A'; j++) temp += arr[j];
            for (int j = 0; j < 26; j++) x = (x * fact(arr[j]));
            arr[c - 'A']--;
            ans = ans + (temp * ((fact(len)) / x));
            len--;
        }
        return ans;
    }
    int main() {
        int i,n;
        string s;
        cin>>s;
        n=s.size();
        cout << solve(s,n);
        return 0;
    }
    

提交回复
热议问题