text: Permutation present at the middle of lexicographic ordering of permutations of at most length N made up integers up to K | C ++ program for the above approach ; Function that finds the middle the lexicographical smallest sequence ; If K is even ; First element is K / 2 ; Remaining elements of the sequence are all integer K ; Stores the sequence when K is odd ; Iterate over the range [ 0 , N / 2 ] ; Check if the sequence ends with in 1 or not ; Remove the sequence ending in 1 ; If it doesn 't end in 1 ; Decrement by 1 ; Insert K to the sequence till its size is N ; Print the sequence stored in the vector ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void lexiMiddleSmallest ( int K , int N ) { if ( K % 2 == 0 ) { cout << K / 2 << " ▁ " ; for ( int i = 0 ; i < N - 1 ; ++ i ) { cout << K << " ▁ " ; } cout << " STRNEWLINE " ; exit ( 0 ) ; } vector < int > a ( N , ( K + 1 ) / 2 ) ; for ( int i = 0 ; i < N / 2 ; ++ i ) { if ( a . back ( ) == 1 ) { a . pop_back ( ) ; } else { -- a . back ( ) ; while ( ( int ) a . size ( ) < N ) { a . push_back ( K ) ; } } } for ( auto i : a ) { cout << i << " ▁ " ; } cout << " STRNEWLINE " ; } int main ( ) { int K = 2 , N = 4 ; lexiMiddleSmallest ( K , N ) ; return 0 ; }