如何获得最大三角形路径和的轨迹?

时间:2015-09-27 11:36:47

标签: r

我现在正努力解决这个最大三角路径求和问题。

此问题来自Euler project - 18

1
8 1
1 2 1
1 5 3 1

我通过最大和和获得总和的路径来解决这种情况。

在这种情况下,答案是1+8+2+5=16c(-1,1,-1)(↓是-1而↘是1)

我知道获得最大金额的代码。

chart[2, 1:2] <- chart[2, 1:2] + chart[1, 1]
for (i in 3:n) {
    chart[i, 1] <- chart[i, 1] + chart[(i - 1), 1]
    chart[i, i] <- chart[i, i] + chart[(i - 1), (i - 1)]
    for (j in 2:(i - 1)) {
        chart[i, j] <- chart[i, j] + max(chart[(i - 1), (j - 1):j])`
        }
    }
}
result <- max(chart[n, ])

Here是此代码的说明页

但我不知道获得最大总和the path的代码。

1 个答案:

答案 0 :(得分:2)

你总是可以追溯。例如:

n <- 4
chart <- read.table("chart2.txt", sep = " ", fill = NA, col.names = 1:n)
chart <- as.matrix(chart)
original <- chart  # keep the original pyramid

chart[2, 1:2] <- chart[2, 1:2] + chart[1, 1]
for (i in 3:n) {
  chart[i, 1] <- chart[i, 1] + chart[(i - 1), 1]
  chart[i, i] <- chart[i, i] + chart[(i - 1), (i - 1)]
  for (j in 2:(i - 1)) {
    chart[i, j] <- chart[i, j] + max(chart[(i - 1), (j - 1):j])
  }
}
result <- max(chart[n, ])
cat("The result is:", result, "\n")

#
# get the path
#
route <- rep(0,n) # route will have n elements
route[n] = which(chart[n,]==max(chart[n,],na.rm=TRUE))[[1]] # index of last max (in last row)
route[1] = 1 # top of the pyramid
for (i in (n-1):2) # starting from bottom, going to top
{
  left <- if (route[i+1] > 1) route[i+1] -1 else 1 # index of left element
  right <- if (route[i+1] < i+1) route[i+1] else i # index of right element
  route[i] = which(chart[i,]==max(chart[i,left], chart[i,right], na.rm=TRUE))[[1]] # choose the higher value
}
cat("Route: ", route)
checksum<-0;
for (i in 1:n) checksum<-checksum+original[i, route[i]]
cat("Checksum:", checksum)

执行时,将打印

Route:  1 1 2 2
Checksum: 16

执行Euler的数据(即n<-15)给出

> cat("Route: ", route)
Route:  1 2 3 3 3 4 4 4 5 6 7 8 9 9 10
> cat("Checksum:", checksum)
Checksum: 1074

(当然route是每行上元素的实际索引,可以很容易地转换为+1-1符号。)