fork(1) download
  1. from collections import Counter
  2.  
  3. for _ in range(int(input())):
  4. n = int(input())
  5. arr = list(map(int, input().split()))
  6. k = int(input())
  7. x = int(input())
  8.  
  9. b = [0] * n
  10.  
  11. # XOR a[i] ^ x
  12. for i in range(n):
  13. b[i] = arr[i] ^ x
  14.  
  15. dif = [0] * n
  16. for i in range(n):
  17. dif[i] = b[i] - arr[i]
  18.  
  19. # sorting according to highest positive difference and preserving index
  20. dif1 = []
  21. for i, j in enumerate(dif):
  22. dif1.append([i, j])
  23.  
  24. dif1.sort(reverse=True, key=lambda x: x[1])
  25.  
  26. # if truth[i] == true then take value from xor array else from intital array (XOR)
  27. truth = [False] * n
  28. temp = 0
  29. temp2 = 0
  30.  
  31. # Count no. whose value has increased
  32. for i in range(n):
  33. if dif1[i][1] >= 0:
  34. temp += 1
  35. # in this check if k<= no. whose value increased, then change their truthh value
  36. # so we can take value from b during final profit
  37. while True:
  38. if k <= temp:
  39. temp2 = temp // k
  40. temp2 = temp2 * k
  41. for i in range(temp2):
  42. truth[dif1[i][0]] = True
  43. temp = temp - temp2
  44. else:
  45. # if k < no. whose value increased after operation, then
  46. # we check the new and old value and accordingly set truth value
  47. new = 0
  48. if temp2 + k <= n:
  49. for i in range(temp2, temp2 + k):
  50. new += b[dif1[i][0]]
  51.  
  52. old = 0
  53. for i in range(temp2, temp2 + k):
  54. old += arr[dif1[i][0]]
  55. if new >= old:
  56. for i in range(temp2, temp2 + k):
  57. truth[dif1[i][0]] = True
  58. break
  59.  
  60. profit = 0
  61. for i in range(n):
  62. # print(profit)
  63. if truth[i]:
  64. profit += b[i]
  65. else:
  66. profit += arr[i]
  67.  
  68. print(profit)
Success #stdin #stdout 0.02s 27712KB
stdin
2
5
1 2 3 4 5
2
4
7
10 15 20 13 2 1 44
4
14
stdout
23
129