Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from sys import stdin, stdout
- import math, heapq
- from collections import deque
- R = lambda : stdin.readline().strip()
- RL = lambda f=None: list(map(f, R().split(' '))) if f else list(R().split(' '))
- output = lambda x: stdout.write(str(x) + '\n')
- output_list = lambda x: output(' '.join(map(str, x)))
- MX = int(2e10) + 5
- n = m=w= 0
- a, dp1, dp2 = [], [], []
- def print_arr(a):
- for i in a:
- print(*i)
- def hash(x, y):
- return str(x)+'#'+str(y)
- def de_hash(s):
- return list(map(int, s.split('#')))
- def is_valid(i, j):
- if -1 <i < n and -1 < j < m:
- return True
- return False
- def bfs(start, dp):
- q = deque()
- q.append(start)
- while len(q):
- i,j = q[0]
- q.popleft()
- for x, y in [[i+1, j], [i, j+1], [i-1, j], [i,j-1]]:
- if is_valid(x, y) and a[i][j] != -1 and dp[x][y] == MX:
- dp[x][y] = min(dp[x][y], dp[i][j] + w)
- q.append([x, y])
- n, m, w = RL(int)
- a = []
- for i in range(n):
- a.append(RL(int))
- dp1 = [ m*[MX] for i in range(n) ]
- dp2 = [ m*[MX] for i in range(n) ]
- dp1[0][0] =0
- bfs([0, 0], dp1)
- dp2[n-1][m-1] =0
- bfs([n-1, m-1], dp2)
- '''
- print_arr(dp1)
- print()
- print_arr(dp2)
- '''
- mn1, mn2 = [MX, ''], [MX, '']
- ans = MX
- for i in range(n):
- for j in range(m):
- if a[i][j] > 0:
- if mn1[0] > dp1[i][j] + a[i][j]:
- mn1 = [dp1[i][j] + a[i][j], hash(i, j)]
- if mn2[0] > dp2[i][j] + a[i][j]:
- mn2 = [dp2[i][j] + a[i][j], hash(i, j)]
- ans = min(ans, dp1[i][j] + dp2[i][j])
- if mn1[1] == mn2[1]:
- i, j = de_hash(mn1[1])
- ans = min(ans,(mn1[0]+mn2[0]-2*a[i][j]) )
- else:
- ans = min(ans, mn1[0]+mn2[0])
- print(ans)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement