File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Input : str[] = "acb"
3+ Output : Rank = 2
4+
5+ Input : str[] = "string"
6+ Output : Rank = 598
7+
8+ Input : str[] = "cba"
9+ Output : Rank = 6
10+ */
11+
12+ // C++ program to find lexicographic rank
13+ // of a string
14+ #include < bits/stdc++.h>
15+ #include < string.h>
16+
17+ using namespace std ;
18+ // A utility function to find factorial of n
19+ int fact (int n)
20+ {
21+ return (n <= 1 ) ? 1 : n * fact (n - 1 );
22+ }
23+
24+ // A utility function to count smaller characters on right
25+ // of arr[low]
26+ int findSmallerInRight (char * str, int low, int high)
27+ {
28+ int countRight = 0 , i;
29+
30+ for (i = low + 1 ; i <= high; ++i)
31+ if (str[i] < str[low])
32+ ++countRight;
33+
34+ return countRight;
35+ }
36+
37+ // A function to find rank of a string in all permutations
38+ // of characters
39+ int findRank (char * str)
40+ {
41+ int len = strlen (str);
42+ int mul = fact (len);
43+ int rank = 1 ;
44+ int countRight;
45+
46+ int i;
47+ for (i = 0 ; i < len; ++i) {
48+ mul /= len - i;
49+
50+ // count number of chars smaller than str[i]
51+ // fron str[i+1] to str[len-1]
52+ countRight = findSmallerInRight (str, i, len - 1 );
53+
54+ rank += countRight * mul;
55+ }
56+
57+ return rank;
58+ }
59+
60+ // Driver program to test above function
61+ int main ()
62+ {
63+ char str[] = " string" ;
64+ cout << findRank (str);
65+ return 0 ;
66+ }
67+
68+ // This code is contributed by Subrat Kumar Swain
You can’t perform that action at this time.
0 commit comments