#include <bits/stdc++.h> using namespace std; // calculating hamming distance int hamdis(string& s1,string& s2) { int dis= 0; int n=s1.length(); for (int i = 0; i < n ; i++) { if (s1[i] != s2[i]) { dis++; } } return dis; } // checking string is binary or not bool checkbinary(string& s) { for (int i = 0; i <s.length() ; i++) { if (s[i] != '0' and s[i]!= '1') { return false; } } return true; } // finding min cost and distance void findminimum(string& str, int a, int b) { if (!checkbinary(str)) { cout << "INVALID"<<endl; return; } string orig = str; sort(str.begin(), str.end()); int origcost = 0; int count01 = 0; int count10 = 0; int m=str.length() - 1; for (int i = 0; i <m ; i++) { if (str[i] == '0' && str[i + 1] == '1') { count01++; origcost += a; } else if (str[i] == '1' && str[i + 1] == '0') { count10++; origcost += b; } } int minHammingDistance = hamdis(str, orig); cout << minHammingDistance << endl; } int main() { int T; cin >> T; for (int t = 0; t < T; t++) { string binaryStr; int A, B; cin >> binaryStr; cin >> A >> B; findminimum(binaryStr, A, B); } return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter