Program to maximize the number of equivalent pairs after swapping in Python


Suppose we have a list of numbers A and list of numbers B of same length. We also have a 2D list of numbers C where each element is of the form [i, j] this indicates we can swap A[i] and A[j] as many times as we want. We have to find the maximum number of pairs where A[i] = B[i] after the swapping.

So, if the input is like A = [5, 6, 7, 8], B = [6, 5, 8, 7], C = [[0, 1],[2, 3]], then the output will be 4, as we can swap A[0] with A[1] then A[2] with A[3].

To solve this, we will follow these steps −

  • N := size of A
  • graph := a graph by attaching given edges bidirectionally.
  • ans := 0
  • seen := a list of size N and fill with False
  • for u in range 0 to N, do
    • if seen[u] is zero, then
      • queue := a queue and insert u
      • seen[u] := True
      • for each node in queue, do
        • for each nei in graph[node], do
          • if seen[nei] is false, then
            • insert nei at the end of queue
            • seen[nei] := True
      • count := a map that contains count of B[i] elements for all i in queue
      • for each i in queue, do
        • if count[A[i]] is non-zero, then
          • count[A[i]] := count[A[i]] - 1
          • ans := ans + 1
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import Counter
class Solution:
   def solve(self, A, B, edges):
      N = len(A)
      graph = [[]
      for _ in range(N)]
         for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)
      ans = 0
      seen = [False] * N
      for u in range(N):
         if not seen[u]:
            queue = [u]
            seen[u] = True
            for node in queue:
               for nei in graph[node]:
                  if not seen[nei]:
                     queue.append(nei)
                     seen[nei] = True
            count = Counter(B[i] for i in queue)
            for i in queue:
               if count[A[i]]:
                  count[A[i]] -= 1
            ans += 1
      return ans
ob = Solution()
A = [5, 6, 7, 8]
B = [6, 5, 8, 7]
C = [[0, 1],[2, 3]]
print(ob.solve(A, B, C))

Input

[5, 6, 7, 8], [6, 5, 8, 7], [[0, 1],[2, 3]]

Output

4

Updated on: 19-Oct-2020

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements