fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Recursive function to calculate factorial of a number
  5. int factorial(int n)
  6. {
  7. return (n <= 2) ? n : n * factorial(n - 1);
  8. }
  9.  
  10. // Function to find Lexicographic rank of a string using
  11. // std::prev_permutation
  12. int findLexicographicRank(string key)
  13. {
  14. string str = key;
  15.  
  16. // sort the string in descending order
  17. sort(str.rbegin(), str.rend());
  18.  
  19. int rank = factorial(str.length()); // maximum rank is n!
  20.  
  21. while(1)
  22. {
  23. // if current permutation is equal to the key, return its rank
  24. if (key == str)
  25. return rank;
  26.  
  27. // find next lexicographically ordered permutation
  28. if (!prev_permutation(str.begin(), str.end()))
  29. break;
  30.  
  31. rank--;
  32. }
  33. }
  34.  
  35. int main()
  36. {
  37. string key = "DCBA";
  38.  
  39. cout << "Lexicographic Rank of " << key << " is "
  40. << findLexicographicRank(key);
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Lexicographic Rank of DCBA is 24