boris-vlasenko

ЕГЭ 18 рекусрия + динамика

Oct 12th, 2020
906
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. f = open('data.txt','r')
  2. a = []
  3. for line in f.readlines():
  4.     #a.append(list(map(int,line.split())))
  5.     row = []
  6.     for x in line.split():
  7.         row.append(int(x))
  8.     a.append(row)
  9. f.close()
  10.  
  11. for r in a:
  12.     print(r)
  13.  
  14. nr = len(a)
  15. nc = len(a[0])
  16.  
  17. s_max = [[None for r in range(nr)] for c in range(nc)] 
  18. s_min = [[None for r in range(nr)] for c in range(nc)] 
  19.  
  20.  
  21. def get_max_sum(r,c):
  22.     global k
  23.     k += 1
  24.     right = None
  25.     down = None
  26.     if c < nc-1:
  27.         if s_max[r][c+1] != None:
  28.             right = s_max[r][c+1]
  29.         else:
  30.             right = get_max_sum(r,c+1)
  31.            
  32.     if r < nr-1:
  33.         if s_min[r+1][c] != None:
  34.             down = s_max[r+1][c]
  35.         else:
  36.             down = get_max_sum(r+1,c)
  37.     if right != None and down != None:
  38.         ss = max(right,down)
  39.     elif right != None and down == None:
  40.         ss = right
  41.     elif right == None and down != None:
  42.         ss = down
  43.     else:
  44.         ss = 0
  45.        
  46.    
  47.     s_max[r][c] = a[r][c] + ss
  48.     return s_max[r][c]
  49.  
  50.  
  51. def get_min_sum(r,c):
  52.     global k
  53.     k += 1
  54.     right = None
  55.     down = None
  56.     if c < nc-1:
  57.         if s_min[r][c+1] != None:
  58.             right = s_min[r][c+1]
  59.         else:
  60.             right = get_min_sum(r,c+1)
  61.            
  62.     if r < nr-1:
  63.         if s_min[r+1][c] != None:
  64.             down = s_min[r+1][c]
  65.         else:
  66.             down = get_min_sum(r+1,c)
  67.     if right != None and down != None:
  68.         ss = min(right,down)
  69.     elif right != None and down == None:
  70.         ss = right
  71.     elif right == None and down != None:
  72.         ss = down
  73.     else:
  74.         ss = 0
  75.        
  76.    
  77.     s_min[r][c] = a[r][c] + ss
  78.     return s_min[r][c]
  79.  
  80. k = 0  
  81. print(get_max_sum(0,0))
  82. print(k)
  83. k = 0
  84. print(get_min_sum(0,0))
  85. print(k)
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment