Check if the array can be sorted only if the elements on given positions can be swapped | C ++ program to check if the array can be sorted only if the elements on the given positions can be swapped ; Function to check if the array can be sorted only if the elements on the given positions can be swapped ; Creating an array for marking the positions ; Iterating through the array and mark the positions ; Iterating through the given array ; If pos [ i ] is 1 , then incrementing till 1 is continuously present in pos ; Sorting the required segment ; Checking if the vector is sorted or not ; Print yes if it is sorted ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void check_vector ( vector < int > A , int n , vector < int > p ) { vector < int > pos ( A . size ( ) ) ; for ( int i = 0 ; i < p . size ( ) ; i ++ ) { pos [ p [ i ] - 1 ] = 1 ; } int flag = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( pos [ i ] == 0 ) continue ; int j = i ; while ( j < n && pos [ j ] ) ++ j ; sort ( A . begin ( ) + i , A . begin ( ) + j + 1 ) ; i = j ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { vector < int > A { 3 , 2 , 1 } ; vector < int > p { 1 , 2 } ; check_vector ( A , A . size ( ) , p ) ; return 0 ; }