如何在最大总和的二维数组中找到元素?

时间:2014-04-06 13:07:11

标签: arrays algorithm sum multidimensional-array elements

我需要找到具有最大总和的二维数组的元素。数组有N行和13列,其中一行中元素的MAXIMAL计数为4,列中元素的数量必须为2.我尝试使用迭代遍历所有组合,但是有更多组合(10 ^ 27)而不是长.MAX_VALUE,当我尝试递归时,它导致了stackoverflow。

可能的解决方案示例:

 _ _ _ _ _ _ _ _ _ _ _ _ _             _ _ _ _ _ _ _ _ _ _ _ _ _ 
|X|X|X|X|_|_|_|_|_|_|_|_|_|M=4        |_|X|_|_|_|X|X|_|_|_|_|_|_| M=3
|X|X|X|X|_|_|_|_|_|_|_|_|_|M=4        |_|_|_|X|X|_|_|X|_|_|X|_|_| M=4
|_|_|_|_|X|X|X|X|_|_|_|_|_|M=4        |_|X|X|X|_|_|_|X|_|_|_|_|_| M=4
|_|_|_|_|X|X|X|X|_|_|_|_|_|M=4    or  |X|_|_|_|_|_|X|_|_|X|_|X|_| M=4
|_|_|_|_|_|_|_|_|X|X|X|_|X|M=4        |_|_|_|_|X|_|_|_|X|X|_|_|_| M=4
|_|_|_|_|_|_|_|_|X|X|X|X|_|M=4        |X|_|_|_|_|_|_|_|X|_|X|_|X| M=4
|_|_|_|_|_|_|_|_|_|_|_|X|X|M=4        |_|_|X|_|_|X|_|_|_|_|_|_|_| M=3
                                      |_|_|_|_|_|_|_|_|_|_|_|X|X| M=2

M是行的前6列和后7列中的最大元数。 我不知道用什么来找到它们。

1 个答案:

答案 0 :(得分:1)

您可以将其解析为max flow problem

这个想法是,流程代表了从游泳者到学科的任务。

你可以分配流量问题中的容量,以满足每个游泳者必须做2个学科的约束,每个学科最多可以有4个游泳者,如下面的Python代码所示,它使用NetworkX库来解决最大问题流动问题。

import networkx as nx

G=nx.DiGraph()

h = [[502,511,0,517,521,0,518,521,507,461,420,556,433,4],
     [0,528,0,451,0 ,445,499,0,459,541,354,479,445, 4],
     [0,524,488,419,0,458,579,0,0,490,565,473,428, 4],
     [0,474,0,476,0,456,483,0,419,470,321,453,384,4],
     [462,496,0,313,394,512,450,462,0,489,302,475,433,4],
     [314,412,316,315,398,413,401,352,0,402,320,391,318,4],
     [353,312,0,255,0,322,321,355,0,346,215,345,250,4]]

# Each row is a discipline
# Each swimmer must do two disciplines
# At most 4 swimmers in any one discipline

num_swimmers = len(h)
num_disciplines = len(h[0])

G.add_node('dest',demand=num_swimmers*2)
A=[]
for i,costs in enumerate(h):
    name='swimmer%d'%i
    A.append(name)
    G.add_node(name,demand=-2) # 2 units of flow start at each swimmer 
    for discipline,cost in enumerate(costs):
        d='discipline%d'%discipline
        G.add_edge(name,d,capacity=1,weight=-cost)
for discipline in range(num_disciplines):
    d='discipline%d'%discipline
    G.add_edge(d,'dest',capacity=4,weight=0) # Can have at most 4 swimmers per discipline

flowdict = nx.min_cost_flow(G)
for swimmer in A:
    for d,flow in flowdict[swimmer].items():
        if flow:
            print swimmer,'->',d

print 'Total cost =',-nx.cost_of_flow(G,flowdict)

打印答案:

swimmer0 -> discipline4
swimmer0 -> discipline11
swimmer1 -> discipline1
swimmer1 -> discipline9
swimmer2 -> discipline6
swimmer2 -> discipline10
swimmer3 -> discipline6
swimmer3 -> discipline3
swimmer4 -> discipline5
swimmer4 -> discipline1
swimmer5 -> discipline5
swimmer5 -> discipline1
swimmer6 -> discipline7
swimmer6 -> discipline0
Total cost = 6790