Couples Holding Hands in C++


Suppose there are N couples and they have sat on 2N seats arranged in a row and want to hold hands. We have to find the minimum number of swaps so that every couple is sitting side by side.

The people and seats are represented by a number from 0 to 2N-1, the couples are numbered in order, this is like the first couple as (0, 1), the second couple as (2, 3), and so on and the last couple as (2N-2, 2N-1).

The couples' initial seating is given by another array called row, and row[i] being the value of the person who is initially sitting in the i-th seat.

So, if the input is like [0,2,4,1,3,5], then the output will be 2

To solve this, we will follow these steps −

  • Define one block of data called UF, in this block define some properties and functions as follows −

  • Define an array parent

  • Initialize the UF block by taking a value N, then do the following −

  • count := N

  • parent := an array of size N

  • for initialize i := 0, when i < N, update (increase i by 1), do −

    • parent[i] := i

  • parent[i] := i

  • parA := getParent(a)

  • parB := getParent(b)

  • if parA is same as parB, then −

    • return

  • (decrease count by 1)

  • parent[parB] := parA

  • Define a function getParent(), this will take i,

  • if parent[i] is same as i, then −

    • return i

  • return parent[i] = getParent(parent[i])

  • From the main method do the following −

  • n := size of row, N := n / 2

  • create one UF block called uf and initialize with N

  • for initialize gr := 0, when gr < N, update (increase gr by 1), do −

    • a := row[gr * 2]

    • b := row[gr * 2 + 1]

    • call unionn(a / 2, b / 2) of uf

  • return N - count of uf

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   class UF{
      public:
      vector<int> parent;
      int count;
      UF(int N){
         count = N;
         parent = vector<int>(N);
         for (int i = 0; i < N; i++) {
            parent[i] = i;
         }
      }
      void unionn(int a, int b){
         int parA = getParent(a);
         int parB = getParent(b);
         if (parA == parB)
         return;
         count--;
         parent[parB] = parA;
      }
      int getParent(int i){
         if (parent[i] == i)
         return i;
         return parent[i] = getParent(parent[i]);
      }
   };
   int minSwapsCouples(vector<int>& row) {
      int n = row.size();
      int N = n / 2;
      UF uf(N);
      for (int gr = 0; gr < N; gr++) {
         int a = row[gr * 2];
         int b = row[gr * 2 + 1];
         uf.unionn(a / 2, b / 2);
      }
      return N - uf.count;
   }
};
main(){
   Solution ob;
   vector<int> v = {0,2,4,1,3,5};
   cout << (ob.minSwapsCouples(v));
}

Input

{0,2,4,1,3,5}

Output

2

Updated on: 08-Jun-2020

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements