Minimize swaps of same | C ++ program for the above approach ; Function to count the number of swaps required to make the sum of ASCII values of the characters of both strings odd ; Initialize alphabets with value ; Initialize values for each alphabet ; Size of the string ; Sum of string S ; Sum of string T ; Stores whether there is any index i such that S [ i ] and T [ i ] have different parities ; Traverse the strings ; Update sum1 and sum2 ; If S [ i ] and T [ i ] have different parities ; If sum1 and sum2 are both odd ; If sum1 and sum2 are both even ; If exists print 1 ; Otherwise ; If sum1 and sum2 are of different parities ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSwaps ( string S , string T ) { int value [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) value [ i ] = i + 1 ; int N = S . size ( ) ; int sum1 = 0 ; int sum2 = 0 ; bool flag = false ; for ( int i = 0 ; i < N ; i ++ ) { sum1 += value [ S [ i ] - ' a ' ] ; sum2 += value [ T [ i ] - ' a ' ] ; if ( ( value [ S [ i ] - ' a ' ] % 2 == 0 && value [ T [ i ] - ' a ' ] % 2 == 1 ) || ( value [ S [ i ] - ' a ' ] % 2 == 1 && value [ T [ i ] - ' a ' ] % 2 == 0 ) ) flag = false ; } if ( sum1 % 2 == 1 && sum2 % 2 == 1 ) cout << "0 STRNEWLINE " ; else if ( sum1 % 2 == 0 && sum2 % 2 == 0 ) { if ( flag ) cout << "1" ; else cout << " - 1" ; } else { cout << " - 1" ; } } int main ( ) { string S = " acd " ; string T = " dbf " ; countSwaps ( S , T ) ; return 0 ; }