当前位置:网站首页>Cf:h. maximum and [bit operation practice + K operations + maximum and]

Cf:h. maximum and [bit operation practice + K operations + maximum and]

2022-07-06 00:44:00 White speed Dragon King's review

analysis

and Just one 0 This position is still 0
So we count 31 individual bit Including 1 The number of
And then greed , From the highest position , As long as there is k Within, we will add ans in ( Add 2 ** i)
This is the bit operation expanded into dict, Then come down greedily from the highest position
Just get a high position , Just make money
So start from the top

ac code

import sys
input = sys.stdin.readline

for _ in range(int(input())):
    n, k = list(map(int, input().split()))
    a = list(map(int, input().split()))

    bitDict = {
    }
    for i in range(31):
        bitDict[i] = 0

    for aa in a:
        #print(bin(aa)[2:].zfill(31))
        bin_str = (bin(aa)[2:].zfill(31))[::-1]
        for i in range(31):
            if bin_str[i] == '1':
                bitDict[i] += 1

    ans = 0
    # greedy
    for i in range(30, -1, -1):
        # normal add 1
        if k >= n - bitDict[i]:
            ans += 2 ** i
            k -= n - bitDict[i]
    print(ans)

summary

An operation + and + greedy

原网站

版权声明
本文为[White speed Dragon King's review]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060036450758.html