Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Codeforce 1957-B : A BIT of a Construction

Problem Link : https://codeforces.com/problemset/problem/1957/B

I have tried this problem by writing this code:

#include <bits/stdc++.h>
using namespace std;
 
int main () {
    unsigned test; cin >> test; // Non-negative
    while (test--) {
        int size, k;
        cin >> size >> k;
        vector<int> v;
        for (int i = 0; i < size; i++) {
            if (k == 0) {
                v.push_back(0);
                continue;
            }
            if (pow(2, i) == k) {
                v.push_back(pow(2, i));
                k -= pow(2, i);
            } else if (pow(2, i) < k && i != size - 1) {
                v.push_back(pow(2, i));
                k -= pow(2, i);
            }
            else {
                v.push_back(k);
                k = 0;
            }
        }
        for (auto as : v) cout << as << ' '; cout << endl;
        return 0;
}

Basically, I tried to generate as many as 10, 100, 1000,.... Because 10|100|1000|... has maximum 1’s after operation I hope. I expect someone will help me by telling what is wrong in this approch.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use left shift operators: 1 << i instead of pow(2, i).
In C++, those kinda functions that you used didn’t give an accurate value.
You also can use this for the maximum value:

1 << (int) log2(k)) - 1

Another is:

k - (1 << (int) log2(k)) - 1)

The rest of the elements are 0. Of course, you have to handle for n = 1.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading