437B - The Child and Set - CodeForces Solution


bitmasks greedy implementation sortings *1500

Please click on ads to support us..

Python Code:

from collections import defaultdict, deque
from functools import lru_cache
from heapq import heappush, heappop
from bisect import bisect_right, bisect_left
from fractions import Fraction as frac
import math
hpop = heappop
hpush = heappush
MOD = 10**9 + 7

def solution():
    
        sum_, limit = map(int, input().split())
    first_bit_map = defaultdict(list) 
    for num in range(1, limit+1):
        first_bit = num & -num
        first_bit_map[first_bit].append(num)
    first_bits = list(sorted(first_bit_map.keys(), reverse=True))
    
    res = []
    i = 0
    while i < len(first_bits) and sum_:
        val = first_bits[i]

        if val > sum_ or len(first_bit_map[val]) == 0:
            i += 1
            continue

        sum_ -= val 
        p = first_bit_map[val].pop()
        res.append(p)

    if sum_ > 0:
        return print(-1)

    print(len(res))
    return print(" ".join(map(str, res)))
            
def main():
    t = 1
        for _ in range(t):
        solution() 
 
main()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<ll> V;
int main()
{ll s,l,i;
cin>>s>>l;
for(i=l;i>0&&s>0;i--)
if(s-(i&-i)>=0)
{s-=(i&-i);
V.push_back(i);}
 
if(s!=0)
cout<<-1;
else
{cout<<V.size()<<endl;
for(i=0;i<V.size();i++)
cout<<V[i]<<" ";}
return 0;
}


Comments

Submit
0 Comments
More Questions

1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro
780C - Andryusha and Colored Balloons
1153A - Serval and Bus
1487C - Minimum Ties
1136A - Nastya Is Reading a Book
1353B - Two Arrays And Swaps
1490E - Accidental Victory
1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR
1435B - A New Technique
1633A - Div 7
268A - Games
1062B - Math
1294C - Product of Three Numbers
749A - Bachgold Problem
1486B - Eastern Exhibition
1363A - Odd Selection