简体   繁体   English

矩阵中的最大路径成本

[英]Maximum path cost in matrix

Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down movement is allowed in a matrix and contains negative cost. 谁能告诉算法在NxM矩阵中找到最大路径成本的算法,该算法从左上角开始到右下角以left,right结束,矩阵中允许向下移动,并且包含负成本。 A cell can be visited any number of times and after visiting a cell its cost is replaced with 0 可以多次访问一个单元,访问单元后其成本将替换为0

Constraints 约束条件
1 <= nxm <= 4x10^6 1 <= nxm <= 4x10 ^ 6
INPUT 输入

4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20

OUTPUT 输出值

37

Explanation is given in the image Explanation of Output 在图像中给出了解释输出解释

Since you have also negative costs then use bellman-ford. 由于您也有负成本,因此请使用Bellman-ford。 What you do is that you change sign of all the costs(convert negative signs to positive and positive to negative) then find the shortest path and this path will be the longest because you have changed the signs. 您要做的是更改所有成本的符号(将负号转换为正号,将正号转换为负号),然后找到最短的路径,这条路径将是最长的,因为您更改了符号。

If the sign is never becoms negative then use dijkstra shrtest-path but before that make all values negative and this will return you the longest path with it's cost. 如果该符号永远不会变成负数,则使用dijkstra shrtest-path,但在此之前将所有值都设为负数,这将以成本的形式返回最长的路径。

You matrix is a direct graph. 矩阵是直接图。 In your image you are trying to find a path(max or min) from index (0,0) to (n-1,n-1). 在您的图像中,您尝试查找从索引(0,0)到(n-1,n-1)的路径(最大或最小)。

You need these things to represent it as a graph. 您需要这些东西才能将其表示为图形。

  • You need a linkedlist and in each node you have a first_Node, second_Node,Cost to move from first node to second . 您需要一个链表,并且在每个节点中都有一个first_Node, second_Node,Cost to move from first node to second
  • An array of linkedlist. 链表的数组。 In each array index you save a linkedlist.If for example there is a path from 0 to 5 and 0 to 1(it's an undirected graph) then your graph will look like this. 在每个数组索引中保存一个链表。例如,如果存在从0到5和0到1的路径(这是一个无向图),则您的图将如下所示。 在此处输入图片说明

If you want a direct-graph then simply add in adj[0] = 5 and do not add in adj[5] = 0 , this means that there is path from 0 to 5 but not from 5 to zero. 如果要直接图,则只需添加adj [0] = 5而不添加adj [5] = 0,这意味着存在从0到5的路径,而不是从5到零的路径。

Here linkedlist represents only nodes which are connected not there cost. 在这里,链表仅表示连接的节点,不增加成本。 You have to add extra variable there which keep cost for each two nodes and it will look like this. 您必须在此处添加额外的变量,以保持每个两个节点的成本,并且看起来像这样。

在此处输入图片说明

Now instead of first linkedlist put this linkedlist in your array and you have a graph now to run shortest or longest path algorithm. 现在,不用第一个链表,而是将此链表放入您的数组中,您现在有了一个图形来运行最短或最长路径算法。

If you want an intellgent algorithm then you can use A* with heuristic, i guess manhattan will be best. 如果您想使用智能算法,则可以将A *与启发式结合使用,我猜曼哈顿将是最好的选择。

If cost of your edges is not negative then use Dijkstra. 如果边缘成本不为负,则使用Dijkstra。

If cost is negative then use bellman-ford algorithm. 如果成本为负,则使用Bellman-ford算法。

You can always find the longest path by converting the minus sign to plus and plus to minus and then run shortest path algorithm. 您始终可以通过将减号转换为加号并将加号转换为减号,然后运行最短路径算法来找到最长路径。 Path founded will be longest. 建立的路径将是最长的。

I answered this question and as you said in comments to look at point two. 我回答了这个问题,正如您在评论中所说的那样,请看第二点。 If that's a task then main idea of this assignment is ensure the Monotonocity . 如果这是一项任务,那么此分配的主要思想是确保Monotonocity

  • h stands for heuristic cost. h代表启发式成本。
  • A stands for accumulated cost. A代表累计成本。

Which says that each node the h(A) =< h(A) + A(A,B) . 也就是说每个节点的h(A) =< h(A) + A(A,B) Means if you want to move from A to B then cost should not be decreasing(can you do something with your values such that this property will hold) but increasing and once you satisfy this condition then everyone node which A* chooses , that node will be part of your path from source to Goal because this is the path with shortest/longest value. 意味着如果要从A移到B则成本不应降低(可以对值进行某些操作以使该属性成立),而应增加,一旦满足此条件,则A *选择的每个节点都将使该节点成为您从源到目标的路径的一部分,因为这是价值最短/最长的路径。

pathMax You can enforece monotonicity. pathMax您可以增强单调性。 If there is path from A to B such that f(S...AB) < f(S ..B) then set cost of the f(S...AB) = Max(f(S...AB) , f(S...A)) where S means source. 如果存在从AB路径,使得f(S ... AB)<f(S ..B),则设置f(S ... AB)的成本= Max(f(S ... AB) ,f(S ... A)),其中S表示来源。

Since moving up is not allowed, paths always look like a set of horizontal intervals that share at least 1 position (for the down move). 由于不允许向上移动,因此路径始终看起来像一组水平间隔,它们共享至少一个位置(对于向下移动)。 Answers can be characterized as, say 答案可以被描述为

struct Answer {
   int layer[N][2]; // layer[i][0] and [i][1] represent interval start&end
                    // with 0 <= layer[i][0] <= layer[i][1] < M
                    // layer[0][0] = 0, layer[N][1] = M-1
                    // and non-empty intersection of layers i and i+1 
};

An alternative encoding is to note only layer widths and offsets to each other; 另一种编码方式是仅注意层的宽度和彼此的偏移量; but you would still have to make sure that the last layer includes the exit cell. 但是您仍然必须确保最后一层包括出口单元。

Assuming that you have a maxLayer routine that finds the highest-scoring interval in each layer (const O(M) per layer), and that all such such layers overlap, this would yield an O(N+M) optimal answer. 假设您有一个maxLayer例程,该例程在每一层中都找到了最高得分间隔(每层常数O(M) ),并且所有这样的层都重叠,那么这将产生O(N+M)最佳答案。 However, it may be necessary to expand intervals to ensure that overlap occurs; 但是,可能有必要扩大间隔以确保发生重叠。 and there may be multiple highest-scoring intervals in a given layer. 并且在给定层中可能会有多个最高得分间隔。 At this point I would model the problem as a directed graph: 在这一点上,我会将问题建模为有向图:

  • each layer has one node per score-maximizing horizontal continuous interval. 每个得分每个得分最大化水平连续间隔有一个节点。
  • nodes from one layer are connected to nodes in the next layer according to the cost of expanding both intervals to achieve at least 1 overlap. 根据扩大两个间隔以实现至少1个重叠的代价,将一层中的节点连接到下一层中的节点。 If they already overlap, the cost is 0. Edge costs will always be zero or negative (otherwise, either source or target intervals could have scored higher by growing bigger). 如果它们已经重叠,则成本为0。边缘成本将始终为零或负(否则,源间隔或目标间隔可能会随着增大而得分更高)。 Add the (expanded) source-node interval value to the connection cost to get an "edge weight". 将(扩展的)源节点间隔值添加到连接成本中以获得“边缘权重”。

You can then run Dijkstra on this graph (negate edge weights so that the "longest path" is returned) to find the optimal path. 然后,您可以在此图上运行Dijkstra(取反边权重,以便返回“最长路径”)以找到最佳路径。 Even better, since all paths pass once and only once through each layer, you only need to keep track of the best route to each node, and only need to build nodes and edges for the layer you are working on. 更好的是,由于所有路径一次穿过每个层一次,因此您只需要跟踪到达每个节点的最佳路线,并且只需要为要处理的层构建节点和边缘即可。

Implementation details ahead 实施细节

  • to calculate maxLayer in O(M), use Kadane's Algorithm , modified to return all maximal intervals instead of only the first. 要计算O(M)中的maxLayer ,请使用经过修改的Kadane算法 ,以返回所有最大间隔,而不是仅返回第一个最大间隔。 Where the linked algorithm discards an interval and starts anew, you would instead keep a copy of that contender to use later. 如果链接算法放弃了一个间隔并重新开始,则应保留该竞争者的副本以供以后使用。

  • given the sample input, the maximal intervals would look like this: 给定样本输入,最大间隔如下所示:

      [0] 1 2 3 -1 -2 [1 2 3] -5 -8 -1 2 -150 => [2] 1 2 3 -250 100 [1 2 3] [100] 1 1 1 1 20 [1 1 1 1 20] [0] 
  • given those intervals, they would yield the following graph: 给定这些间隔,它们将产生以下图形:

      (0) | =>0 (+6) \\ -1=>5 \\ (+2) =>7/ \\ -150=>-143 / \\ (+7) (+100) =>12 \\ / =>-43 \\ / (+24) | =>37 (0) 
  • when two edges incide on a single node (row 1 1 1 1 20), carry forward only the highest incoming value. 当两个边沿在单个节点上倾斜(行1 1 1 1 20)时,仅结转最高输入值。

For each element in a row, find the maximum cost that can be obtained if we move horizontally across the row, given that we go through that element. 对于一行中的每个元素,如果我们在该行中进行水平移动,则找到如果我们在该行中水平移动,则可以获得的最大成本。

Eg. 例如。 For the row 对于行

1 2 3 -1 -2

The maximum cost for each element obtained if we move horizontally given that we pass through that element will be 如果我们通过该元素水平移动,则获得的每个元素的最大成本为

6 6 6 5 3

Explanation: 说明:

for element 3: we can move backwards horizontally touching 1 and 2. we will not move horizontally forward as the values -1 and -2, reduces the cost value. 对于元素3:我们可以向后水平触摸1和2。因为值-1和-2会降低成本值,所以我们不会水平向前移动。

So the maximum cost for 3 = 1 + 2 + 3 = 6 因此,最大成本为3 = 1 + 2 + 3 = 6

The maximum cost matrix for each of elements in a row if we move horizontally, for the input you have given in the description will be 如果我们水平移动,则一行中每个元素的最大成本矩阵,对于您在描述中给出的输入,将为

6     6    6    5      3  
-5   -7    1    2      -148  
6     6    6    -144   100  
24    24   24   24     24

Since we can move vertically from one row to the below row, update the maximum cost for each element as follows: 由于我们可以从一行垂直移到下一行,因此,如下更新每个元素的最大费用:

cost[i][j] = cost[i][j] + cost[i-1][j]

So the final cost matrix will be : 因此,最终成本矩阵为:

6    6    6     5      3 
1    -1   7     7      -145 
7    5    13    -137   -45  
31   29   37    -113   -21 

Maximum value in the last row of the above matrix will be give you the required output ie 37 上述矩阵最后一行的最大值将为您提供所需的输出,即37

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM