Advertisement
dark-Matter

g

May 5th, 2021
775
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. from sys import stdin, stdout
  2. import math, heapq
  3. from collections import deque
  4.  
  5. R = lambda : stdin.readline().strip()
  6. RL = lambda f=None: list(map(f, R().split(' '))) if f else list(R().split(' '))
  7.  
  8. output = lambda x: stdout.write(str(x) + '\n')
  9. output_list = lambda x: output(' '.join(map(str, x)))
  10.  
  11. MX = int(2e10) + 5
  12. n = m=w= 0
  13. a, dp1, dp2 = [], [], []
  14.  
  15. def print_arr(a):
  16.     for i in a:
  17.         print(*i)
  18.  
  19. def hash(x, y):
  20.     return str(x)+'#'+str(y)
  21.  
  22. def de_hash(s):
  23.     return list(map(int, s.split('#')))
  24.  
  25.  
  26. def is_valid(i, j):
  27.     if -1 <i < n and -1 < j < m:
  28.         return True
  29.     return False
  30.  
  31. def bfs(start, dp):
  32.     q = deque()
  33.     q.append(start)
  34.     while len(q):
  35.         i,j = q[0]
  36.         q.popleft()
  37.         for x, y in [[i+1, j], [i, j+1], [i-1, j], [i,j-1]]:
  38.             if is_valid(x, y) and a[i][j] != -1 and dp[x][y] == MX:
  39.                 dp[x][y] = min(dp[x][y], dp[i][j] + w)
  40.                 q.append([x, y])
  41.      
  42.                    
  43. n, m, w = RL(int)
  44. a = []
  45. for i in range(n):
  46.     a.append(RL(int))
  47. dp1 = [ m*[MX] for i in range(n) ]
  48. dp2 = [ m*[MX] for i in range(n) ]
  49. dp1[0][0] =0
  50. bfs([0, 0], dp1)
  51. dp2[n-1][m-1] =0
  52. bfs([n-1, m-1], dp2)
  53. '''
  54. print_arr(dp1)
  55. print()
  56. print_arr(dp2)
  57. '''
  58. mn1, mn2 = [MX, ''], [MX, '']
  59. ans = MX
  60.  
  61. for i in range(n):
  62.     for j in range(m):
  63.         if a[i][j] > 0:
  64.             if mn1[0] > dp1[i][j] + a[i][j]:
  65.                 mn1 = [dp1[i][j] + a[i][j], hash(i, j)]
  66.             if mn2[0] > dp2[i][j] + a[i][j]:
  67.                 mn2 = [dp2[i][j] + a[i][j], hash(i, j)]
  68.             ans = min(ans, dp1[i][j] + dp2[i][j])
  69.  
  70. if mn1[1] == mn2[1]:
  71.     i, j = de_hash(mn1[1])
  72.     ans  =  min(ans,(mn1[0]+mn2[0]-2*a[i][j]) )
  73. else:
  74.     ans = min(ans, mn1[0]+mn2[0])
  75.  
  76. print(ans)
  77.  
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement