Given two arrays A[] and B[] consisting of N positive integers and a matrix List[][] consisting of M pairs of indices, the task is to minimize the count of unequal same-indexed elements(Ai != Bi) from the two arrays by swapping between any pair of given indices in array A[].
Examples:
Input: N = 5, M = 4, A[] = {1, 5, 9, 2, 3}, B[] = {2, 4, 5, 1, 3}, List[][] = {{1, 4}, {2, 3}, {3, 5}, {2, 5}}
Output: 1
Explanation:
Initial array A[] = {1, 5, 9, 2, 3}
Swapping indices (1, 4) in A[] = {2, 5, 9, 1, 3}
Swapping indices (2, 3) in A[] = {2, 9, 5, 1, 3}
Therefore, on comparing the final array A[] (= {2, 9, 5, 1, 3}) with array B[] (= {2, 4, 5, 1, 3}), the only pair of unequal same-indexed elements is A[2] != B[2] (1-based indexing)Input: N = 5, M = 4, A[] = {1, 10, 19, 6, 2}, B[] = {1, 6, 10, 2, 19}, List[][] = {{1, 4}, {2, 3}, {3, 5}, {2, 5}}
Output: 2
Approach: Since the elements of the array A[] specified in the list of pairs can be swapped any number of times, those elements can be considered as a connected set with swaps within its elements allowed. Below are the steps to implement this approach:
- Traverse the given array A[] and create a set of connected components that can be easily done using the disjoint set.
- For each element in B[] find if the corresponding element in A[] (A[i], B[i]) belong to the same connected component or not.
- If Yes, make A[i]=B[i] and continue. Else, increment the count of mismatched pairs.
- Print the count of mismatched pair after all the above steps.
Below is the implementation of the above approach :
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;
int find( int par[], int x);
void unionn( int par[], int a, int b);
// Function that count of the mismatched // pairs in both the array int countPairs( int A[], int B[], int N,
int M, int List[][2])
{ int count = 0;
// Create a parent array
// and initialize it
int par[N + 1];
for ( int i = 0; i <= N; i++)
par[i] = i;
// Preprocessing of the given
// pairs of indices
for ( int i = 0; i < M; i++)
{
// 1-based indexing
int index1 = find(par, List[i][0] - 1);
int index2 = find(par, List[i][1] - 1);
// If both indices doesn't belong
// to same component
if (index1 != index2)
{
// Insert the indices in
// same component
unionn(par, index1, index2);
}
}
// Map to get the indices
// of array A
map< int , int > mp;
for ( int i = 0; i < N; i++)
{
mp[A[i]] = i;
}
for ( int i = 0; i < N; i++)
{
if (A[i] != B[i])
{
// If current element is not
// present in array B then
// count this as mismatched
if (mp.find(B[i]) == mp.end())
{
count++;
continue ;
}
// Get the index of the element
// in array B
int j = mp[B[i]];
// Check if both indices belong
// to same connected component
// if not increment the count
if (find(par, i) != find(par, j))
count++;
}
}
// Return answer
return count;
} // Function that gives the connected // component of each index int find( int par[], int x)
{ if (par[x] == x)
return x;
else
return par[x] = find(par, par[x]);
} // Function that creates the // connected components void unionn( int par[], int a, int b)
{ // Find parent of a and b
// recursively
a = find(par, a);
b = find(par, b);
if (a == b)
return ;
// Update the parent of a
par[a] = b;
} // Driver Code int main()
{ int N = 5;
int M = 4;
// Given arrays A[], B[]
int A[] = { 1, 5, 9, 2, 3 };
int B[] = { 2, 4, 5, 1, 3 };
// List of indices
int List[][2] = { { 1, 4 }, { 2, 3 },
{ 3, 5 }, { 2, 5 } };
// Function call
cout << countPairs(A, B, N, M, List);
return 0;
} // This code is contributed by rutvik_56 |
// Java program for the above approach import java.util.*;
class GFG {
// Function that count of the mismatched
// pairs in both the array
public static int countPairs( int A[], int B[],
int N, int M,
int [][] List)
{
int count = 0 ;
// Create a parent array
// and initialize it
int par[] = new int [N + 1 ];
for ( int i = 0 ; i <= N; i++)
par[i] = i;
// Preprocessing of the given
// pairs of indices
for ( int i = 0 ; i < M; i++) {
// 1-based indexing
int index1
= find(par, List[i][ 0 ] - 1 );
int index2
= find(par, List[i][ 1 ] - 1 );
// If both indices doesn't belong
// to same component
if (index1 != index2) {
// Insert the indices in
// same component
union(par, index1, index2);
}
}
// HashMap to get the indices
// of array A
HashMap<Integer, Integer> map
= new HashMap<>();
for ( int i = 0 ; i < N; i++) {
map.put(A[i], i);
}
for ( int i = 0 ; i < N; i++) {
if (A[i] != B[i]) {
// If current element is not
// present in array B then
// count this as mismatched
if (!map.containsKey(B[i])) {
count++;
continue ;
}
// Get the index of the element
// in array B
int j = map.get(B[i]);
// Check if both indices belong
// to same connected component
// if not increment the count
if (find(par, i) != find(par, j))
count++;
}
}
// Return answer
return count;
}
// Function that gives the connected
// component of each index
public static int find( int par[],
int x)
{
if (par[x] == x)
return x;
else
return par[x]
= find(par, par[x]);
}
// Function that creates the
// connected components
public static void
union( int par[], int a, int b)
{
// Find parent of a and b
// recursively
a = find(par, a);
b = find(par, b);
if (a == b)
return ;
// Update the parent of a
par[a] = b;
}
// Driver Code
public static void
main(String[] args)
{
int N = 5 ;
int M = 4 ;
// Given arrays A[], B[]
int A[] = { 1 , 5 , 9 , 2 , 3 };
int B[] = { 2 , 4 , 5 , 1 , 3 };
// List of indices
int List[][]
= { { 1 , 4 }, { 2 , 3 },
{ 3 , 5 }, { 2 , 5 } };
// Function Call
System.out.println(
countPairs(A, B, N, M, List));
}
} |
# Python3 program for the above approach # Function that count of the mismatched # pairs in both the array def countPairs(A, B, N, M, List ):
count = 0
# Create a parent array
# and initialize it
par = [ 0 ] * (N + 1 )
for i in range (N + 1 ):
par[i] = i
# Preprocessing of the given
# pairs of indices
for i in range (M):
# 1-based indexing
index1 = find(par, List [i][ 0 ] - 1 )
index2 = find(par, List [i][ 1 ] - 1 )
# If both indices doesn't belong
# to same component
if (index1 ! = index2):
# Insert the indices in
# same component
union(par, index1, index2)
# HashMap to get the indices
# of array A
map = {}
for i in range (N):
map [A[i]] = i
for i in range (N):
if (A[i] ! = B[i]):
# If current element is not
# present in array B then
# count this as mismatched
if (B[i] not in map .keys()):
count + = 1
continue
# Get the index of the element
# in array B
j = map [B[i]]
# Check if both indices belong
# to same connected component
# if not increment the count
if (find(par, i) ! = find(par, j)):
count + = 1
# Return answer
return count
# Function that gives the connected # component of each index def find(par, x):
if (par[x] = = x):
return x
else :
par[x] = find(par, par[x])
return par[x]
# Function that creates the # connected components def union(par, a, b):
# Find parent of a and b
# recursively
a = find(par, a)
b = find(par, b)
if (a = = b):
return
# Update the parent of a
par[a] = b
# Driver Code N = 5
M = 4
# Given arrays A[], B[] A = [ 1 , 5 , 9 , 2 , 3 ]
B = [ 2 , 4 , 5 , 1 , 3 ]
# List of indices List = [ [ 1 , 4 ], [ 2 , 3 ],
[ 3 , 5 ], [ 2 , 5 ] ]
# Function call print (countPairs(A, B, N, M, List ))
# This code is contributed by Shivam Singh |
// C# program for the above approach using System;
using System.Collections.Generic;
class GFG{
// Function that count of the mismatched
// pairs in bot the array
public static int countPairs( int [] A, int [] B, int N,
int M, int [, ] List)
{
int count = 0;
// Create a parent array
// and initialize it
int [] par = new int [N + 1];
for ( int i = 0; i <= N; i++)
par[i] = i;
// Preprocessing of the given
// pairs of indices
for ( int i = 0; i < M; i++)
{
// 1-based indexing
int index1 = find(par, List[i, 0] - 1);
int index2 = find(par, List[i, 1] - 1);
// If both indices doesn't belong
// to same component
if (index1 != index2)
{
// Insert the indices in
// same component
union(par, index1, index2);
}
}
// Dictionary to get the indices
// of array A
Dictionary< int , int > map = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
if (map.ContainsKey(A[i]))
map[A[i]] = i;
else
map.Add(A[i], i);
}
for ( int i = 0; i < N; i++)
{
if (A[i] != B[i])
{
// If current element is not
// present in array B then
// count this as mismatched
if (!map.ContainsKey(B[i]))
{
count++;
continue ;
}
// Get the index of the element
// in array B
int j = map[B[i]];
// Check if both indices belong
// to same connected component
// if not increment the count
if (find(par, i) != find(par, j))
count++;
}
}
// Return answer
return count;
}
// Function that gives the connected
// component of each index
public static int find( int [] par, int x)
{
if (par[x] == x)
return x;
else
return par[x] = find(par, par[x]);
}
// Function that creates the
// connected components
public static void union( int [] par, int a, int b)
{
// Find parent of a and b
// recursively
a = find(par, a);
b = find(par, b);
if (a == b)
return ;
// Update the parent of a
par[a] = b;
}
// Driver Code
public static void Main(String[] args)
{
int N = 5;
int M = 4;
// Given arrays []A, []B
int [] A = {1, 5, 9, 2, 3};
int [] B = {2, 4, 5, 1, 3};
// List of indices
int [, ] List = {{1, 4}, {2, 3}, {3, 5}, {2, 5}};
// Function Call
Console.WriteLine(countPairs(A, B, N, M, List));
}
} // This code is contributed by shikhasingrajput |
<script> // Javascript program for the above approach // Function that count of the mismatched // pairs in bot the array function countPairs(A, B, N, M, List)
{ var count = 0;
// Create a parent array
// and initialize it
var par = Array(N+1);
for ( var i = 0; i <= N; i++)
par[i] = i;
// Preprocessing of the given
// pairs of indices
for ( var i = 0; i < M; i++)
{
// 1-based indexing
var index1 = find(par, List[i][0] - 1);
var index2 = find(par, List[i][1] - 1);
// If both indices doesn't belong
// to same component
if (index1 != index2)
{
// Insert the indices in
// same component
unionn(par, index1, index2);
}
}
// Map to get the indices
// of array A
var mp = new Map();
for ( var i = 0; i < N; i++)
{
mp.set(A[i], i);
}
for ( var i = 0; i < N; i++)
{
if (A[i] != B[i])
{
// If current element is not
// present in array B then
// count this as mismatched
if (!mp.has(B[i]))
{
count++;
continue ;
}
// Get the index of the element
// in array B
var j = mp.get(B[i]);
// Check if both indices belong
// to same connected component
// if not increment the count
if (find(par, i) != find(par, j))
count++;
}
}
// Return answer
return count;
} // Function that gives the connected // component of each index function find(par,x)
{ if (par[x] == x)
return x;
else
return par[x] = find(par, par[x]);
} // Function that creates the // connected components function unionn(par, a, b)
{ // Find parent of a and b
// recursively
a = find(par, a);
b = find(par, b);
if (a == b)
return ;
// Update the parent of a
par[a] = b;
} // Driver Code var N = 5;
var M = 4;
// Given arrays A[], B[] var A = [1, 5, 9, 2, 3];
var B = [2, 4, 5, 1, 3];
// List of indices var List = [ [ 1, 4 ], [ 2, 3 ],
[ 3, 5 ], [ 2, 5 ] ];
// Function call document.write( countPairs(A, B, N, M, List)); // This code is contributed by itsok. </script> |
1
Time Complexity: O(N + M)
Auxiliary Space: O(N)