976A. Minimum Binary Number

Implementation

String can be called correct if it consists of characters “0” and “1” and there are no redundant leading zeroes. Here are some examples: “0”, “10”, “1001”.

You are given a correct string s.

You can perform two different operations on this string:

  1. swap any pair of adjacent characters (for example, “101” → “110”);
  2. replace “11” with “1” (for example, “110” → “10”).

Let val(s) be such a number that s is its binary representation.

Correct string a is less than some other correct string b iff val(a) < val(b).

Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).

Hints

Hint 1

How to reduce a binary number? Reduce the number of digits.

Solution

Given a binary number as string consisting of 1s and 0s. The number is to be minimized by performing operations mentioned in the problem. The idea is to reduce the number of digits. This can be carried out using operation 2 since one ‘1’ is deleted if two ‘1’s are together. So bring all the ‘1’s together by performing operation 1 and perform operation 2 till only one ‘1’ remains.

Any given string can be rearranged such that all the ‘1’s are in the beginning and all except one ‘1’ can be deleted. We can find the minimized number even without doing these operations explicitly. For that we take the count of ones and zeros in the given string. Since the given string is always a correct one the binary number will always contain at least one ‘1’ in the beginning or the number itself will be zero. So if num_ones is less than 1 the answer is zero and we can straight away print it. Otherwise the answer will be ‘1’ followed by given number of zeros since we can remove all the other ‘1’s.

Code

#include<bits/stdc++.h>
using namespace std;
int main() {
    int n, num_zeros=0, num_ones=0;
    cin >> n >> s;
    
    //To take count of zeros and ones
    for(int i=0;i<n;++i) {
        if(s[i]=='0') num_zeros++;
        else num_ones++;
    }
    
    //To check the corner case when input is 0
    if(num_ones < 1){
        cout << 0 << endl;
        return 0;
    }
    else cout<<1;
    //To print the zeros.
    for(int i=0;i<num_zeros;++i) cout << 0;
}

Written by Aswanth