text: Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition | C ++ program for the above approach ; Function to find the minimum number of swaps ; New array to convert to 1 - based indexing ; Keeps count of swaps ; Check if it is an ' X ' position ; Corner Case ; Swap ; Print the minimum swaps ; Driver Code ; Given Number N ; Given Permutation of N numbers ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( vector < int > & P , int n ) { vector < int > arr ; arr . push_back ( 0 ) ; for ( auto x : P ) arr . push_back ( x ) ; int cnt = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == i ) { swap ( arr [ i ] , arr [ i + 1 ] ) ; cnt ++ ; } } if ( arr [ n ] == n ) { swap ( arr [ n - 1 ] , arr [ n ] ) ; cnt ++ ; } cout << cnt << endl ; } signed main ( ) { int N = 9 ; vector < int > P = { 1 , 2 , 4 , 9 , 5 , 8 , 7 , 3 , 6 } ; solve ( P , N ) ; return 0 ; }