动态规划之最优二叉查找树
Posted Keep--Silent
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划之最优二叉查找树相关的知识,希望对你有一定的参考价值。
核心:
c
n
t
(
i
,
j
)
=
s
u
m
(
p
[
k
]
cnt(i,j)=sum(p[k]
cnt(i,j)=sum(p[k] for k in range(i, j + 1)
)
)
)
if
i
>
j
i>j
i>j:
d
p
[
i
]
[
j
]
=
0
dp[i][j]=0
dp[i][j]=0
else:
d
p
[
j
]
[
j
]
=
m
a
x
(
d
p
[
i
]
[
k
]
+
d
p
[
k
+
2
]
[
j
]
+
c
n
t
(
i
,
j
)
dp[j][j]=max(dp[i][k]+dp[k+2][j]+cnt(i,j)
dp[j][j]=max(dp[i][k]+dp[k+2][j]+cnt(i,j) for k in (i-1,j)
)
)
)
class OptimalBinarySearchTree:
def __init__(self, p):
self.p = p
self.dp =
self.ans =
def find(self, i, j):
if (i, j) in self.dp:
return self.dp[(i, j)]
elif i > j:
return int(0)
else:
self.dp[(i, j)] = int(1e9)
cnt = sum(p[k] for k in range(i, j + 1))
for k in range(i - 1, j):
self.dp[(i, j)] = min(self.dp[(i, j)], self.find(i, k) + self.find(k + 2, j) + cnt)
return self.dp[(i, j)]
if __name__ == '__main__':
p = [0, 0.1, 0.2, 0.4, 0.3]
s = OptimalBinarySearchTree(p)
print(s.p)
print(s.find(1, 4))
for it in s.dp:
print(it,":",s.dp[it])
以上是关于动态规划之最优二叉查找树的主要内容,如果未能解决你的问题,请参考以下文章