Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
- #define ll long long
- #define ld double
- #define llu long long unsigned
- int minSwaps( vector < ll > arr, int n )
- {
- vector < pair<ll, ll> > arrPos;
- for (int i = 0; i < n; i++)
- {
- arrPos.push_back( make_pair( arr[i] , i ) );
- }
- sort( arrPos.begin() , arrPos.end() );
- vector < pair<ll, ll> > arrPosRev = arrPos;
- reverse( arrPosRev.begin() , arrPosRev.end() );
- vector <bool> vis(n, false);
- int ans1 = 0;
- for (int i = 0; i < n; i++)
- {
- if (vis[i] || arrPos[i].second == i)
- continue;
- int cycle_size = 0;
- int j = i;
- while (!vis[j])
- {
- vis[j] = 1;
- j = arrPos[j].second;
- cycle_size++;
- }
- if (cycle_size > 0)
- {
- ans1 += (cycle_size - 1);
- }
- }
- // 2
- vector <bool> vis2(n, false);
- int ans2 = 0;
- for (int i = 0; i < n; i++)
- {
- if (vis2[i] || arrPosRev[i].second == i)
- continue;
- int cycle_size = 0;
- int j = i;
- while (!vis2[j])
- {
- vis2[j] = 1;
- j = arrPosRev[j].second;
- cycle_size++;
- }
- if (cycle_size > 0)
- {
- ans2 += (cycle_size - 1);
- }
- }
- return min( ans1 , ans2 );
- }
- int main()
- {
- fast;
- int n;
- cin>>n;
- vector < ll > v;
- for( int i = 0 ; i < n ; i++ )
- {
- ll x;
- cin>>x;
- v.push_back(x);
- }
- cout<<minSwaps( v , n )<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement