Advertisement
Shiam7777777

Untitled

Jan 19th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
  4. #define ll long long
  5. #define ld double
  6. #define llu long long unsigned
  7.  
  8. int minSwaps( vector < ll > arr, int n )
  9. {
  10.     vector < pair<ll, ll> > arrPos;
  11.     for (int i = 0; i < n; i++)
  12.     {
  13.         arrPos.push_back( make_pair( arr[i] , i ) );
  14.     }
  15.  
  16.     sort( arrPos.begin() , arrPos.end() );
  17.     vector < pair<ll, ll> > arrPosRev = arrPos;
  18.     reverse( arrPosRev.begin() , arrPosRev.end() );
  19.  
  20.     vector <bool> vis(n, false);
  21.  
  22.     int ans1 = 0;
  23.  
  24.     for (int i = 0; i < n; i++)
  25.     {
  26.  
  27.         if (vis[i] || arrPos[i].second == i)
  28.             continue;
  29.  
  30.         int cycle_size = 0;
  31.         int j = i;
  32.         while (!vis[j])
  33.         {
  34.             vis[j] = 1;
  35.  
  36.             j = arrPos[j].second;
  37.             cycle_size++;
  38.         }
  39.  
  40.         if (cycle_size > 0)
  41.         {
  42.             ans1 += (cycle_size - 1);
  43.         }
  44.     }
  45. //          2
  46.     vector <bool> vis2(n, false);
  47.  
  48.     int ans2 = 0;
  49.  
  50.     for (int i = 0; i < n; i++)
  51.     {
  52.  
  53.         if (vis2[i] || arrPosRev[i].second == i)
  54.             continue;
  55.  
  56.         int cycle_size = 0;
  57.         int j = i;
  58.         while (!vis2[j])
  59.         {
  60.             vis2[j] = 1;
  61.  
  62.             j = arrPosRev[j].second;
  63.             cycle_size++;
  64.         }
  65.  
  66.         if (cycle_size > 0)
  67.         {
  68.             ans2 += (cycle_size - 1);
  69.         }
  70.     }
  71.     return min( ans1 , ans2 );
  72. }
  73.  
  74. int main()
  75. {
  76.     fast;
  77.     int n;
  78.     cin>>n;
  79.     vector < ll > v;
  80.  
  81.     for( int i = 0 ; i < n ; i++ )
  82.     {
  83.         ll x;
  84.         cin>>x;
  85.         v.push_back(x);
  86.     }
  87.  
  88.     cout<<minSwaps( v , n )<<endl;
  89.  
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement