Difference between lexicographical ranks of two given permutations | C ++ program for the above approach ; Function the print the difference between the lexicographical ranks ; Store the permutations in lexicographic order ; Intital permutation ; Initial variables ; Check permutation ; Initialize second permutation ; Check permutation ; Print difference ; Driver Code ; Given array P [ ] ; Given array Q [ ] ; Given size ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findDifference ( vector < int > & p , vector < int > & q , int N ) { vector < int > A ( N ) ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; bool IsCorrect ; int a = 1 , b = 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != p [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; a ++ ; } while ( next_permutation ( A . begin ( ) , A . end ( ) ) ) ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != q [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; b ++ ; } while ( next_permutation ( A . begin ( ) , A . end ( ) ) ) ; cout << abs ( a - b ) << endl ; } int main ( ) { vector < int > p = { 1 , 3 , 2 } ; vector < int > q = { 3 , 1 , 2 } ; int n = p . size ( ) ; findDifference ( p , q , n ) ; return 0 ; }