arrays - Maximize sum of array after applying the given operations on the array
问题描述
Given an Array A consisting of N elements and an integer K. You can perform following operations on array any number of times(Can be 0).
Choose an element from array A. Let us denote as A[i]
Choose a positive integer Y.
Change A[i] to A[i] xor Y.
The Sum of all the Y's used in the operations should not be greater than K.
Your task is to find the maximum sum of all the elements of array A after operations.
Example:-
N=5
K=6
A={9,7,7,4,3}
Output:- 36
Explanation:- In the first operation, choose the fourth element and Y=2. Then change 4 to 4 xor 2, that is 6. the updated array will be:- 9,7,7,6,3
In second Operation, choose the fifth element and Y=4. Then change 3 to 3 xor 4, that is 7. The updated array will be 9,7,7,6,7 Hence sum is 36.
Please someone explain the logic behind the problem. I am not getting the idea.
解决方案
Since you didn't clarify my comment about Y
I will assume that the answer is no, you can not count unique Y
values once towards the budget K
.
This problem is simply a modified 0-1 knapsack problem in disguise. To solve it using the knapsack problem:
Let the item value & weight pairs be defined as the set
I = { (Y ^ a - a, Y) : a \in A, Y \in {1,K}}
Apply the dynamic programming solution to the 0-1 knapsack problem with weight limit K
, and the requirement that only one item may be picked per a \in A
. The total optimal weight of the knapsack problem + any unmodified a \in A
is the solution.
Here is an implementation in python that solves the example given.
#!/usr/bin/python
def solve2(w,v,W,nK):
n = len(w)
m = dict()
for j in range(0,W+1):
m[-1, j] = 0
for i in range(-1,n):
m[i, 0] = 0
for i in range(0,n):
for j in range(0,W+1):
b_w = -1
b_v = -1
found = False
for k in range(0,nK):
if w[i][k] <= j and v[i][k] >= b_v:
b_w = w[i][k]
b_v = v[i][k]
found = True
if found:
m[i, j] = max(m[i-1, j], m[i-1, j-b_w] + b_v)
else:
m[i, j] = m[i-1, j]
return m[n-1,W]
A = [9,7,7,4,3]
K = 6
v = [ [ (Y^a)-a for Y in range(1,K+1) ] for a in A]
w = [ [ Y for Y in range(1,K+1) ] for a in A]
print ('Solution value is:', sum(A) + solve2(w,v,K,K))
推荐阅读
- python - 基于标签的重叠聚类(软聚类)
- delphi - Delphi 10.3.2 - 无法解析单元名称 System.Classes
- javafx - javafx 如何获取特定的 tabvleview 单元格索引?
- regex - 需要在两个分隔符之间生成正则表达式
- javascript - 使用 lodash 在带有整数的数组中查找字符串元素包括不工作
- directory - 如何在终端中根据列表(包含文件名和目标路径)移动文件?
- php - 使用 laravel 应用程序导入大型 excel 文件
- android - SAF - 检查文件夹 Uri 存在的方法总是产生 true
- html - MP4 视频不能在 iPhone 上播放,但可以在桌面和 Android 上播放
- python-3.x - 如何对大数据框进行子集化以加快执行速度?