lecture5_P3_dynamic_programming_bst.py
1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import P3_utility
class Node:
def __init__(self,data):
self.l_child=None
self.r_child=None
self.data = data
def tree(key,r,i,j):
k=r[i][j]
if(k==0):
return
else:
p=Node(key[k])
p.l_child=tree(key,r,i,k-1)
p.r_child=tree(key,r,k+1,j)
return p
key=[" ","A","B","C","D"]
p=[0,0.375, 0.375, 0.125,0.125]
n=len(p)-1
a=[[0 for j in range(0,n+2)] for i in range(0,n+2)]
r=[[0 for j in range(0,n+2)] for i in range(0,n+2)]
for i in range (1,n+1):
a[i][i-1]=0
a[i][i]=p[i]
r[i][i]=i
r[i][i-1]=0
a[n+1][n]=0
r[n+1][n]=0
for dia in range(1,n):
for i in range(1,n-dia+1):
j=i+dia
small=1000
for k in range(i,j+1):
psum=0
for y in range(i,j+1):
psum+=p[y]
t=a[i][k-1]+a[k+1][j]+psum
if( t< small):
small = t
a[i][j]=t
r[i][j]=k
P3_utility.printMatrixF(a)
print()
P3_utility.printMatrix(r)
root=tree(key,r,1,n)
P3_utility.print_inOrder(root)
print()
P3_utility.print_preOrder(root)