Problem:
 Score : 400 points    Problem Statement You are given N non-negative integers A_1, A_2, ..., A_N and another non-negative integer K .  For a integer X between 0 and K (inclusive), let f(X) = (X XOR A_1)  +  (X XOR A_2)  +  ...  +  (X XOR A_N) .  Here, for non-negative integers a and b , a XOR b denotes the bitwise exclusive OR of a and b .  Find the maximum value of f .   What is XOR?  The bitwise exclusive OR of a and b , X , is defined as follows:   When X is written in base two, the digit in the 2^k 's place ( k \geq 0 ) is 1 if, when written in base two, exactly one of A and B has 1 in the 2^k 's place, and 0 otherwise.   For example, 3 XOR 5 = 6 . (When written in base two: 011 XOR 101 = 110 .)

Solution (Python):
import sys
input = sys.stdin.readline


def read():
    N, K = map(int, input().strip().split())
    A = list(map(int, input().strip().split()))
    return N, K, A


def solve(N, K, A):
    L = max(K, max(A), 1).bit_length()
    k = [0 for i in range(L)]
    i = 0
    while K:
        k[i] += K & 1
        i += 1
        K >>= 1
    b = [0 for i in range(L)]
    for a in A:
        i = 0
        x = a
        while x:
            b[i] += x & 1
            i += 1
            x >>= 1
    k = k[::-1]
    b = b[::-1]
    
    
    dp = [[-1, -1] for i in range(L+1)]
    dp[0][1] = 0
    for i in range(L):
        if dp[i][0] >= 0:
            dp[i+1][0] = (dp[i][0] << 1) + max(b[i], N-b[i])
        if dp[i][1] >= 0:
            if k[i] == 1:
                dp[i+1][0] = max(dp[i+1][0], (dp[i][1] << 1) + b[i])
                dp[i+1][1] = (dp[i][1] << 1) + (N-b[i])
            else:
                dp[i+1][1] = (dp[i][1] << 1) + (b[i])
    return max(dp[L][1], dp[L][0])


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def digit_bin(n):
    cnt = 1
    while n > 1:
        n = n >> 1
        cnt += 1
    return cnt


def main():
    N, K = LI()
    A = LI()
    M = max(K, max(A))
    n = digit_bin(M)
    one_count = [0] * n
    pow2 = [1] * (n+1)

    for i in range(1, n+1):
        pow2[i] = pow2[i-1] * 2

    for a in A:
        i = 0
        while a:
            if a & 1 == 1:
                one_count[i] += 1
            i += 1
            a = a >> 1
    
    
    cur = 0
    ans = 0
    for i in range(n)[::-1]:
        
        b = 0
        if one_count[i] <= N - one_count[i]:
            b = 1
            if cur + pow2[i] > K:
                b = 0
        cur += pow2[i] * b
        if b == 1:
            ans += pow2[i] * (N-one_count[i])
        else:
            ans += pow2[i] * one_count[i]

    print(ans)


main()

Solution (Python):
def resolve():
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))
    dp = [[-1 for _ in range(2)] for __ in range(45)]
    dp[0][0] = 0

    for i in range(40):
        mask = 1<<(40-i-1)
        one_num = 0
        for a in A:
            if a & mask:
                one_num += 1
        costdiff0 = mask*one_num
        costdiff1 = mask*(N-one_num)
        if dp[i][1] != -1:
            dp[i+1][1] = max(dp[i+1][1], dp[i][1]+max(costdiff0, costdiff1))
        if dp[i][0] != -1 and K&mask: 
            dp[i+1][1] = max(dp[i+1][1], dp[i][0]+costdiff0)
        if dp[i][0] != -1:
            if K&mask:
                dp[i+1][0] = max(dp[i+1][0], dp[i][0]+costdiff1)
            else:
                dp[i+1][0] = max(dp[i+1][0], dp[i][0]+costdiff0)
    print(max(dp[40][0], dp[40][1]))

    

if '__main__' == __name__:
    resolve()

Solution (Python):


N, K = list(map(int, input().split()))
A = list(map(int, input().split()))

b = 1 << 63
X = 0
ans = 0

for i in range(64):
    cnt = 0
    for a in A:
        if a & b:
            cnt += 1
    if N >= cnt*2 and (X ^ b) <= K:
        X ^= b
        ans += (N - cnt) * b
    else:
        ans += cnt * b
    b >>= 1
print(ans)

Solution (Python):
N, K = map(int, input().split())
As = list(map(int, input().split()))
bitK = K.bit_length()
ans = [0]*bitK
for a in As:
    for i in range(bitK):
        if not (a>>i)&1:
            ans[i] += 1

ans = ans[::-1]
string = ['0']*bitK
if bitK==0:
    print(sum(As))
else:
    for i, a in enumerate(ans):
        if a>=N/2:
            string[i] = '1'
            if int(''.join(string), 2)>K:
                string[i] = '0'
    num = int(''.join(string), 2)
    print(sum([x^num for x in As]))

Solution (Python):
N,K = map(int,input().split())
A = list(map(int,input().split()))
UP = max(A)
UL = UP.bit_length()
KL = K.bit_length()
L = max(UL,KL)
INF = float("inf")

dp = [[-INF] * 2 for _ in range(L+1)]
dp[0][0]=0
ZF = True
for i in range(1,L+1): 
  fac = pow(2,L-i)
  one = 0; zero = 0
  keta = L-i
  if K>>keta&1 == 1:
    ZF = False
  
  for j in range(N): 
    if A[j]>>keta&1 == 1: 
      one +=1
    else:
      zero +=1
  one,zero = zero,one
  MAX = max(one,zero)
  
  if K>>keta&1 == 1: 
    dp[i][0] = dp[i-1][0]+fac*one
  else:
    dp[i][0] = dp[i-1][0]+fac*zero
  
  if ZF: 
    dp[i][1] = 0
  else:
    if K>>keta&1 == 1: 
      dp[i][1] = max(dp[i-1][1]+fac*MAX,dp[i-1][0]+fac*zero)
    else: 
      dp[i][1] = dp[i-1][1]+fac*MAX

ans = max(dp[L][0],dp[L][1])
print(ans)

Solution (Python):
from sys import stdin, stdout
input = stdin.readline
print = stdout.write

n, k = map(int, input().split())
arr = [int(i) for i in input().split()]

bit = [0] * 44
for i in arr:
    for j, b in enumerate(bin(i)[2:].zfill(44)):
        bit[j] += (ord(b) - ord('0'))


res = 0
for i in range(44):
    val = 2 ** (43 - i)
    if (n - bit[i]) > bit[i] and k >= val:
        res += (n - bit[i]) * val
        k -= val
    else:
        res += bit[i] * val
print(str(res))

Solution (Python):
N, K = map(int, input().split())
A = [int(i) for i in input().split()]
BC = [0 for _ in range(40)]
for a in A:
    for i, b in enumerate(bin(a)[2:].zfill(40)):
        if b == '0':
            BC[i] += 1


ans = 0
for i in range(40):
    if BC[i] > N//2 and K >= 2**(39-i):
        K -= 2**(39-i)
        ans += 2**(39-i)*BC[i]
    else:
        ans += 2**(39-i)*(N-BC[i])
print(ans)

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7






N, K = getNM()
A = getList()
lista = [[0, 0] for i in range(61)]

def splitbit(n):
    for i in range(61):
        if n & (1 << i):
            lista[i][0] += 1
        else:
            lista[i][1] += 1
for i in A:
    splitbit(i)

ans = 0
cnt = 0
for i in range(60, -1, -1):
    if lista[i][1] > lista[i][0] and cnt + 2 ** i <= K:
        cnt += 2 ** i
        ans += lista[i][1] * 2 ** i
    else:
        ans += lista[i][0] * 2 ** i
print(ans)

Solution (Python):
n,k = map(int,input().split())
A = list(map(int,input().split()))
cnt = [0]*50
L = format(k, 'b').zfill(50)
S = [[0,0] for _ in range(50)]
for a in A:
    a_ = format(a, 'b').zfill(50)
    for i in range(50):
        if a_[i]=='1':
            S[i][0] += 1
        else:
            S[i][1] += 1
for i in range(len(S)):
    S[i][0] *= pow(2, 50-i-1)
    S[i][1] *= pow(2, 50-i-1)
dp = [[-1,-1] for _ in range(55)]
dp[0][0] = 0
for i in range(50):
    if L[i] == '1':
        if dp[i][1] != -1:
            dp[i+1][1] = dp[i][1] + max(S[i][0], S[i][1])
        if dp[i][0] != -1:
            dp[i+1][1] = max(dp[i+1][1], dp[i][0]+S[i][0])
            dp[i+1][0] = dp[i][0] + S[i][1]
    else:
        if dp[i][1] != -1:
            dp[i+1][1] = dp[i][1] + max(S[i][1], S[i][0])
        if dp[i][0] != -1:
            dp[i+1][0] = dp[i][0] + S[i][0]
print(max(dp[50]))

Solution (Python):
n,k = map(int,input().split())
A = list(map(int,input().split()))
cnt = [0]*50
L = format(k, 'b').zfill(50)
S = [[0,0] for _ in range(50)]
for a in A:
    a_ = format(a, 'b').zfill(50)
    for i in range(50):
        if a_[i]=='1':
            S[i][0] += 1
        else:
            S[i][1] += 1
for i in range(len(S)):
    S[i][0] *= pow(2, 50-i-1)
    S[i][1] *= pow(2, 50-i-1)

dp = [[-1,-1] for _ in range(55)]
dp[0][0] = 0

for i in range(50):
    
    if L[i] == '1':
        if dp[i][1] != -1:
            dp[i+1][1] = dp[i][1] + max(S[i][0], S[i][1])
        if dp[i][0] != -1:
            dp[i+1][1] = max(dp[i+1][1], dp[i][0]+S[i][0])
            dp[i+1][0] = dp[i][0] + S[i][1]
        
            
    else:
        if dp[i][1] != -1:
            dp[i+1][1] = dp[i][1] + max(S[i][1], S[i][0])
        if dp[i][0] != -1:
            dp[i+1][0] = dp[i][0] + S[i][0]

print(max(dp[50]))

Solution (Python):
n,k=map(int,input().split())
l=list(map(int,input().split()))
m=max(l)
table=[[0,0]for i in range(m.bit_length())]
now=0
su=0
cor=1<<(m.bit_length()-1)
for i in range(m.bit_length()):
    p=[0,0]
    for j in range(n):
        p[l[j]%2]+=1
        l[j]//=2
    table[i][0]=p[0]
    table[i][1]=p[1]
if k.bit_length()>m.bit_length():
    now+=k>>m.bit_length()<<m.bit_length()
    su+=now*n
for i in range(m.bit_length()-1,-1,-1):
    p=table[i]
    if p[1]<=p[0] and now+cor<=k:
        su+=p[0]*cor
        now+=cor
    else:
        su+=cor*p[1]
    cor//=2
print(su)

Solution (Python):
def f_max(X, digit):
    if X == 0:
        return sum([Ad[i] * (2**i) for i in range(digit)])
    elif X == 2**digit - 1:
        return sum([max(Ad[i], N - Ad[i]) * (2**i) for i in range(digit)])
    elif X >= 2**(digit-1):
        return max((N - Ad[digit-1]) * (2**(digit-1)) + f_max(X-2**(digit-1), digit-1), Ad[digit-1] * (2**(digit-1)) + f_max(2**(digit-1)-1, digit-1))
    else:
        return Ad[digit-1] * (2**(digit-1)) + f_max(X, digit-1)

N, K = map(int, input().split())
K_max, digits = 2*10**12, 0
while K_max > 0:
    K_max >>= 1
    digits += 1

Ad = [0]*digits
for a in list(map(int, input().split())):
    for i in range(digits):
        Ad[i] += a % 2
        a >>= 1

print(f_max(K, digits))

Solution (Python):
import math

N,K = map(int,input().split())
A = list(map(int,input().split()))
D = len(bin(max(A))) - 2
O = max(len(bin(K)) - 2,D)
M = N / 2

L = [0] * D
C = [1] * O

for a in A:
  s = str(bin(a))[2:]
  l = list(s.zfill(D))
  L = [int(i) + j for i,j in zip(l,L)]
      
L = (O - D) * [0] + L

x = 0

for i in range(O):
  tmp = 0
  if L[i] < M:
    tmp = 2 ** abs(O - i - 1)
    if x + tmp <= K:
      x += tmp

ans = 0

for a in A:
  ans += x ^ a
  
print(ans)

Solution (Python):
from sys import setrecursionlimit
setrecursionlimit(10 ** 7)

n,k = map(int,input().split())
a = list(map(int,input().split()))

bit_sum = [0]*40
keta = [0]*40

for i in a:
    for j in range(40):
        if i&2**j == 2**j:
            bit_sum[j] += 1

k_bit = [0]*40
flag = False

for i in range(40):
    if k&2**i == 2**i:
        k_bit[i] = 1

def count(ke,flag):
    if ke == -1:
        return 0
    if k_bit[ke] == 1:
        if flag:
            return max(2**ke*bit_sum[ke],2**ke*(n-bit_sum[ke]))+count(ke-1,flag)
        else:
            if 2**ke*(n-bit_sum[ke]) > 2**ke*bit_sum[ke]:
                return 2**ke*(n-bit_sum[ke])+count(ke-1,flag)
            else:
                flag = True
                return 2**ke*bit_sum[ke]+count(ke-1,flag)
    else:
        if flag:
            return max(2**ke*bit_sum[ke],2**ke*(n-bit_sum[ke]))+count(ke-1,flag)
        else:
            return 2**ke*bit_sum[ke]+count(ke-1,flag)

print(count(39,False))

Solution (Python):
from sys import setrecursionlimit
setrecursionlimit(10 ** 7)

n,k = map(int,input().split())
a = list(map(int,input().split()))

bit_sum = [0]*40
keta = [0]*40

for i in a:
    for j in range(40):
        if i&2**j == 2**j:
            bit_sum[j] += 1

k_bit = [0]*40
flag = False

for i in range(40):
    if k&2**i == 2**i:
        k_bit[i] = 1

def count(ke):
    global flag
    if ke == -1:
        return 0
    if k_bit[ke] == 1:
        if flag:
            return max(2**ke*bit_sum[ke],2**ke*(n-bit_sum[ke]))+count(ke-1)
        else:
            if 2**ke*(n-bit_sum[ke]) > 2**ke*bit_sum[ke]:
                return 2**ke*(n-bit_sum[ke])+count(ke-1)
            else:
                flag = True
                return 2**ke*bit_sum[ke]+count(ke-1)
    else:
        if flag:
            return max(2**ke*bit_sum[ke],2**ke*(n-bit_sum[ke]))+count(ke-1)
        else:
            return 2**ke*bit_sum[ke]+count(ke-1)

print(count(39))

Solution (Python):
n,k = map(int,input().split())
ai = [int(i) for i in input().split()]

tmp = format(max(k,max(ai)), 'b')

lng = len(tmp)
tmp = format(k, '0'+str(lng)+'b')

li = [0]*(lng)
ai_li = [0]*(n)

for i in range(n):
    
    
    
    ai_li[i] = format(ai[i], '0'+str(lng)+'b')

add_enb_flag = False

for i in range(lng):
    cnt = 0
    for j in range(n):
        if ai_li[j][i] == '1':
            cnt += 1
    
    if cnt >= (n+1) // 2:
        if tmp[i] == "1":
            add_enb_flag = True
        li[i] = 0
    elif tmp[i] == '1' or add_enb_flag == True:
        li[i] = 1
    else:
        li[i] = 0
k_m = 0
bai = 1

for i in range(lng):
    k_m += li[lng-i-1] *bai
    bai *= 2


        
ans = 0
for i in range(n):
    ans += k_m^ai[i]
    
print(ans)

Solution (Python):
import sys
import math
import bisect
def input():
    return sys.stdin.readline()[:-1]
n,k = map(int,input().split())
a = list(map(int,input().split()))
ans = 0
keta = 0
lis = []

tt = k
num=0
while tt!=0:
    tt//=2
    num+=1

if k==0:
    num=1
num=48
for _ in range(num):
    tmp = 0
    for i in range(n):
        if a[i]%2==0:
            tmp+=1
        a[i]//=2
    lis.append([tmp,n-tmp])
    keta+=1
dp = [[0 for i in range(2)]for i in range(num+1)]
dp[0][0]=0
for i in range(1,num+1):
    jum = k>>(num-i)&1
    dp[i][0] += dp[i-1][0]+lis[num-i][1-jum]*2**(num-i)
    if dp[i-1][1] and jum==0:
        dp[i][1] += dp[i-1][1]+max(lis[num-i])*2**(num-i)
    elif dp[i-1][1] and jum==1:
        dp[i][1] += max(dp[i-1][1]+max(lis[num-i])*2**(num-i),dp[i-1][0]+lis[num-i][jum]*2**(num-i))
    elif dp[i-1][1]==0 and jum==1:
        dp[i][1] += dp[i-1][0]+lis[num-i][jum]*2**(num-i)

print(max(dp[-1]))

Solution (Python):
from sys import stdin
def main():
    
    readline=stdin.readline
    n,k=map(int,readline().split())
    a=list(map(int,readline().split()))

    s=bin(max(k,max(a)))[2:]
    l=len(s)
    cnt_one=[0]*l

    for i in range(n):
        b=a[i]
        for j in range(l):
            if b&1==1:
                cnt_one[j]+=1
            b>>=1

    cnt_one.reverse()
    k_bin=bin(k)[2:]
    dp=[[-float("inf"),-float("inf")] for _ in range(l+1)]
    dp[0][0]=0
    for i in range(l):
        j=l-i
        score1=cnt_one[i]*2**(j-1)
        score2=(n-cnt_one[i])*2**(j-1)
        if len(k_bin)<j:
            dp[i+1][0]=dp[i][0]+score1
        else:
            if k_bin[len(k_bin)-j]=="1":
                dp[i+1][0]=dp[i][0]+score2
                if cnt_one[i]>=(n+1)//2:  
                    dp[i+1][1]=max(dp[i][0]+score1,dp[i][1]+score1)
                else:  
                    dp[i+1][1]=max(dp[i][0]+score1,dp[i][1]+score2)
            else:
                dp[i+1][0]=dp[i][0]+score1
                if cnt_one[i]>=(n+1)//2:  
                    dp[i+1][1]=dp[i][1]+score1
                else:  
                    dp[i+1][1]=dp[i][1]+score2

    print(max(dp[l][0],dp[l][1]))

if __name__=="__main__":
    main()

Solution (Python):
from sys import stdin
def main():
    
    readline=stdin.readline
    n,k=map(int,readline().split())
    a=list(map(int,readline().split()))

    s=bin(max(k,max(a)))[2:]
    l=len(s)
    cnt_one=[0]*l

    for i in range(n):
        b=a[i]
        for j in range(l):
            if b&1==1:
                cnt_one[j]+=1
            b>>=1

    cnt_one.reverse()
    k_bin=bin(k)[2:]
    dp=[[-float("inf"),-float("inf")] for _ in range(l+1)]
    dp[0][0]=0
    for i in range(l):
        j=l-i
        if len(k_bin)<j:
            dp[i+1][0]=dp[i][0]+cnt_one[i]*2**(j-1)
        else:
            if k_bin[len(k_bin)-j]=="1":
                dp[i+1][0]=dp[i][0]+(n-cnt_one[i])*2**(j-1)
                if cnt_one[i]>=(n+1)//2:  
                    dp[i+1][1]=max(dp[i][0]+cnt_one[i]*2**(j-1),dp[i][1]+cnt_one[i]*2**(j-1))
                else:  
                    dp[i+1][1]=max(dp[i][0]+cnt_one[i]*2**(j-1),dp[i][1]+(n-cnt_one[i])*2**(j-1))
            else:
                dp[i+1][0]=dp[i][0]+cnt_one[i]*2**(j-1)
                if cnt_one[i]>=(n+1)//2:  
                    dp[i+1][1]=dp[i][1]+cnt_one[i]*2**(j-1)
                else:  
                    dp[i+1][1]=dp[i][1]+(n-cnt_one[i])*2**(j-1)

    print(max(dp[l][0],dp[l][1]))

if __name__=="__main__":
    main()

Solution (Python):
from sys import stdin
def main():
    
    readline=stdin.readline
    n,k=map(int,readline().split())
    a=list(map(int,readline().split()))

    s=bin(max(k,max(a)))[2:]
    l=len(s)
    cnt_one=[0]*l

    for i in range(n):
        b=a[i]
        for j in range(l):
            if b&1==1:
                cnt_one[j]+=1
            b>>=1

    cnt_one.reverse()
    k_bin=bin(k)[2:]
    dp=[[-float("inf"),-float("inf")] for _ in range(l+1)]
    dp[0][0]=0
    for i in range(l):
        j=l-i
        if len(k_bin)<j:
            dp[i+1][0]=dp[i][0]+cnt_one[i]*2**(j-1)
        else:
            if k_bin[len(k_bin)-j]=="1":
                dp[i+1][0]=dp[i][0]+(n-cnt_one[i])*2**(j-1)
                if cnt_one[i]>=n//2:  
                    dp[i+1][1]=max(dp[i][0]+cnt_one[i]*2**(j-1),dp[i][1]+cnt_one[i]*2**(j-1))
                else:  
                    dp[i+1][1]=max(dp[i][0]+cnt_one[i]*2**(j-1),dp[i][1]+(n-cnt_one[i])*2**(j-1))
            else:
                dp[i+1][0]=dp[i][0]+cnt_one[i]*2**(j-1)
                if cnt_one[i]>=(n+1)//2:  
                    dp[i+1][1]=dp[i][1]+cnt_one[i]*2**(j-1)
                else:  
                    dp[i+1][1]=dp[i][1]+(n-cnt_one[i])*2**(j-1)

    print(max(dp[l][0],dp[l][1]))

if __name__=="__main__":
    main()

Solution (Python):
n,k = map(int,input().split())
A = list(map(int,input().split()))

b = 1
c = 0
while b <= k:
  b *= 2
  c += 1

B = [0]*(c)
for a in A:
  for i in range(c):
    if a>>i & 1 :      
      B[i] += 1
      
x = 0
for b in range(c,-1,-1):
  if x + (1<<b) > k:
    continue
  if B[b] < (n+1)//2:
    x += 1<<b
    
ans = 0
for a in A:
  ans += x^a
print(ans)

Solution (Python):
def main():
    n, k, *a = map(int, open(0).read().split())

    cnt = [sum((x >> i) & 1 for x in a) for i in range(40)]
    bits = [0 if i > n - i else 1 for i in cnt]

    base = format(k, 'b')
    l = len(base)
    tmp = []

    if sum(2 ** i for i, b in enumerate(bits[:l]) if b == 1) > k:
        for i in range(l - 1, -1, -1):
            if int(base[-i - 1]) < bits[i]:
                bits[i] = 0
                tmp.append(sum(2 ** j for j, b in enumerate(bits[:l]) if b == 1))
    else:
        tmp.append(sum(2 ** j for j, b in enumerate(bits[:l]) if b == 1))

    ans = max(sum(i ^ x for x in a) for i in tmp if i <= k)
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def examA():
    bit = 41
    N, K = LI()
    A = LI()
    B = [0]*bit
    for a in A:
        for j in range(bit):
            if a&(1<<j)>0:
                B[j] += 1
    ans = 0
    cnt = 0
    for i in range(bit)[::-1]:
        if N-B[i]<=B[i]:
            ans += (1 << i) * B[i]
        else:
            if cnt+(1<<i)>K:
                ans += (1 << i) * B[i]
            else:
                cnt += (1 << i)
                ans += (1 << i) * (N-B[i])
    print(ans)
    return

def examA2():
    bit = 41
    N, K = LI()
    A = LI()
    B = [0]*bit
    ans = 0
    for a in A:
        for j in range(bit):
            if a&(1<<j)>0:
                B[j] += 1
        ans += K^a
    for i in range(bit):
        if (1<<i)&K==0:
            continue
        cnt = 0
        cnt += (1<<i) * B[i]
        for j in range(i+1,bit):
            f = (1<<j)&K
            if f==0:
                cnt += (1 << j) * B[j]
            else:
                cnt += (1 << j) * (N-B[j])
        for j in range(i):
            cnt += max(N-B[j],B[j])*(1<<j)
        ans = max(ans,cnt)
    print(ans)
    return

def examB():
    N, K = LI()
    WP = [LI()for _ in range(N)]
    l = 0; r = 101
    for _ in range(100):
        now = (l+r)/2
        W = [0]*N
        for i,(w,p) in enumerate(WP):
            W[i] = w*(p-now)
        W.sort(reverse=True)
        if sum(W[:K])>=0:
            l = now
        else:
            r = now
    ans = l
    print(ans)
    return

def examC():
    class UnionFind():
        def __init__(self, n):
            self.parent = [-1 for _ in range(n)]
            

        def find(self, x):
            
            if self.parent[x] < 0:
                return x
            else:
                self.parent[x] = self.find(self.parent[x])
                return self.parent[x]

        def unite(self, x, y):
            
            x, y = self.find(x), self.find(y)
            if x == y:
                return False
            else:
                if self.size(x) < self.size(y):
                    x, y = y, x
                self.parent[x] += self.parent[y]
                self.parent[y] = x

        def same(self, x, y):
            
            return self.find(x) == self.find(y)

        def size(self, x):
            
            x = self.find(x)
            return -self.parent[x]

        def is_root(self, x):
            
            return self.parent[x] < 0

        def roots(self):
            
            return [i for i, x in enumerate(self.parent) if x < 0]

        def members(self, x):
            
            root = self.find(x)
            return [i for i in range(self.n) if self.find(i) == root]

        def group_count(self):
            
            return len(self.roots())

        def all_group_members(self):
            
            return {r: self.members(r) for r in self.roots()}
    N, M = LI()
    Uf = UnionFind(N)
    for _ in range(M):
        a, b = LI()
        a -= 1; b -= 1
        Uf.unite(a,b)
    size = [Uf.size(0),Uf.size(1)]
    size.sort()
    rest = N-sum(size)
    size[1] += rest
    ans = size[0]*(size[0]-1)//2 + size[1]*(size[1]-1)//2 - M
    print(ans)
    return

def examD():
    
    class segment_():
        def __init__(self, A, n, segfunc, ide_ele=0):
            
            self.ide_ele = ide_ele
            
            self.num = 1 << (n - 1).bit_length()
            self.seg = [self.ide_ele] * 2 * self.num
            self.segfunc = segfunc
            
            for i in range(n):
                self.seg[i + self.num] = A[i]
                
            for i in range(self.num - 1, 0, -1):
                self.seg[i] = self.segfunc(self.seg[2 * i], self.seg[2 * i + 1])

        def update(self, k, r):
            k += self.num
            self.seg[k] = r
            while k:
                k >>= 1
                self.seg[k] = self.segfunc(self.seg[k * 2], self.seg[k * 2 + 1])

        
        def add(self, k, x=1):
            k += self.num
            self.seg[k] += x
            while k:
                k >>= 1
                self.seg[k] = self.segfunc(self.seg[k * 2], self.seg[k * 2 + 1])

        def query(self, p, q):
            
            if q < p:
                return self.ide_ele
            p += self.num;
            q += self.num
            res = self.ide_ele
            while p < q:
                if p & 1 == 1:
                    res = self.segfunc(res, self.seg[p])
                    p += 1
                if q & 1 == 1:
                    q -= 1
                    res = self.segfunc(res, self.seg[q])
                p >>= 1;
                q >>= 1
            return res

    N, Q = LI()
    X = LI()
    X.append(inf)
    X.insert(0,-inf)
    Seg = segment_(X, (N+1), lambda a, b: a + b)
    ans = [0]*Q
    for q in range(Q):
        C, D = LI()
        l1 = bisect.bisect_left(X,C-D)
        r1 = bisect.bisect_left(X,C)
        cntl = r1-l1
        cnt1 = C*cntl-Seg.query(l1,r1)
        l2 = bisect.bisect_left(X,C)
        r2 = bisect.bisect_left(X,C+D)
        cntr = r2-l2
        cnt2 = Seg.query(l2,r2)-C*cntr
        
        ans[q] = cnt1+cnt2+D*(N-cntl-cntr)
    for v in ans:
        print(v)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examA2()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Solution (Python):
def examA():
    bit = 41
    N, K = LI()
    A = LI()
    B = [0]*bit
    for a in A:
        for j in range(bit):
            if a&(1<<j)>0:
                B[j] += 1
    ans = 0
    cnt = 0
    for i in range(bit)[::-1]:
        if N-B[i]<=B[i]:
            ans += (1 << i) * B[i]
        else:
            if cnt+(1<<i)>K:
                ans += (1 << i) * B[i]
            else:
                cnt += (1 << i)
                ans += (1 << i) * (N-B[i])
    print(ans)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examA()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
MOD = 10 ** 9 + 7

N, K = map(int, input().split())
A = list(map(int, input().split()))
C = [1] * 50
for i in range(50 - 1):
    C[i + 1] = 2 * C[i]

count = [0] * 50

for i in range(N):
    a = A[i]
    j = 0
    while a:
        if a % 2 == 1:
            count[j] += 1
        j += 1
        a //= 2

B = [0] * 60
k = K
j = 0
while k:
    if k % 2 == 1:
        B[j] = 1
    j += 1
    k //= 2

under = [-1] * (j + 1)
just = [0] * (j + 1)


tmp = 0
for i in range(49, j - 1, -1):
    tmp += C[i] * count[i]

for i in range(j - 1, -1, -1):
    tmp1 = count[i] 
    tmp0 = N - tmp1 
    if B[i] == 0:
        just[i] = just[i + 1] + C[i] * tmp1
        if under[i + 1] >= 0:
            under[i] = under[i + 1] + C[i] * max(tmp1, tmp0)
    else: 
        just[i] = just[i + 1] + C[i] * tmp0
        if under[i + 1] == -1:
            under[i] = just[i + 1] + C[i] * tmp1
        if under[i + 1] >= 0:
            under[i] = under[i + 1] + C[i] * max(tmp1, tmp0)
            under[i] = max(under[i], just[i + 1] + C[i] * tmp1)


print (max(under[0], just[0]) + tmp)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
MOD = 10 ** 9 + 7

N, K = map(int, input().split())
A = list(map(int, input().split()))

count = [0] * 50

for i in range(N):
    a = A[i]
    j = 0
    while a:
        if a % 2 == 1:
            count[j] += 1
        j += 1
        a //= 2

B = [0] * 60
k = K
j = 0
while k:
    if k % 2 == 1:
        B[j] = 1
    j += 1
    k //= 2

under = [-1] * (j + 1)
just = [0] * (j + 1)


tmp = 0
for i in range(49, j - 1, -1):
    tmp += pow(2, i) * count[i]

for i in range(j - 1, -1, -1):
    tmp1 = count[i] 
    tmp0 = N - tmp1 
    if B[i] == 0:
        just[i] = just[i + 1] + pow(2, i) * tmp1
        if under[i + 1] >= 0:
            under[i] = under[i + 1] + pow(2, i) * max(tmp1, tmp0)
    else: 
        just[i] = just[i + 1] + pow(2, i) * tmp0
        if under[i + 1] == -1:
            under[i] = just[i + 1] + pow(2, i) * tmp1
        if under[i + 1] >= 0:
            under[i] = under[i + 1] + pow(2, i) * max(tmp1, tmp0)
            under[i] = max(under[i], just[i + 1] + pow(2, i) * tmp1)


print (max(under[0], just[0]) + tmp)

Solution (Python):
n, k = map(int, input().split())
A = list(map(int, input().split()))

k_bin = "{:040b}".format(k)
A_bin = list(map(lambda x: '{:040b}'.format(x), A))
dp = [[0]*2 for _ in range(41)]
for i, col in enumerate(zip(*A_bin)):
    zero_cnt = col.count('0')
    one_cnt = n-zero_cnt

    p = 40-i-1

    if dp[i][0] != 0:
        dp[i+1][0] = dp[i][0]+max(zero_cnt, one_cnt)*2**p

    if k_bin[i] == '0':
        dp[i+1][1] = dp[i][1]+one_cnt*2**p
    else:
        dp[i+1][0] = max(dp[i+1][0], dp[i][1]+one_cnt*2**p)
        dp[i+1][1] = dp[i][1]+zero_cnt*2**p

print(max(dp[-1]))

Solution (Python):
n, k = map(int, input().split())
A = list(map(int, input().split()))

k_bin = "{:040b}".format(k)
A_bin = list(map(lambda x: '{:040b}'.format(x), A))

X = ''
limited = 1
for i, col in enumerate(zip(*A_bin)):
    if k_bin[i] == '0' and limited:
        X += '0'
        continue

    zero_cnt = col.count('0')
    one_cnt = n-zero_cnt
    if one_cnt < zero_cnt:
        X += '1'
    else:
        X += '0'
        limited = 0

X = int(X, 2)
print(sum(X ^ a for a in A))