Advertisement
Guest User

Untitled

a guest
May 26th, 2015
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. import copy
  2. import sys
  3. def greater_path(path1,path2):
  4. (path_list1,elevation1,last_heightl1) = path1
  5. (path_list2,elevation2,last_heightl2) = path2
  6. len1 = len(path_list1)
  7. len2 = len(path_list2)
  8. if len1 != len2:
  9. return len1 > len2
  10. return elevation1 > elevation2
  11.  
  12. def get_neighbours(arrsize,point):
  13. rcount,ccount = arrsize
  14. i,j = point
  15. deltas = [(-1,0),(0,-1),(1,0),(0,1)]
  16. points = ((x+i,y+j) for (x,y) in deltas)
  17. points = filter(lambda (x,y): (x>=0 and x<rcount) and (y >= 0 and y<ccount),points)
  18. return points
  19.  
  20. def is_higher(arr,point1,point2):
  21. i,j = point1
  22. ii,jj = point2
  23. return arr[i][j] < arr[ii][jj]
  24.  
  25. def split_neighbours(neighbours,arr,i,j):
  26. higher,lower = [],[]
  27. higher = filter(lambda (x,y): is_higher(arr,(i,j),(x,y)),neighbours)
  28. lower = filter(lambda (x,y): not is_higher(arr,(i,j),(x,y)),neighbours)
  29. return higher,lower
  30.  
  31. def get_max(path1,path2):
  32. return path1 if greater_path(path1,path2) else path2
  33.  
  34. def update_paths(paths,arr,i,j):
  35. elevation = arr[i][j]
  36. arrsize = len(arr),len(arr[0])
  37. neighbours = get_neighbours(arrsize,(i,j))
  38. higher_neighbours,lower_neighbours = split_neighbours(neighbours,arr,i,j)
  39. lower_paths = [paths[neighbour] for neighbour in lower_neighbours if paths.get(neighbour) is not None]
  40. if lower_paths == []:
  41. paths[(i,j)]=([(i,j)],0,elevation)
  42. else:
  43. path,elevation_sofar,last_elevation = reduce(get_max,lower_paths)
  44. path = copy.deepcopy(path)
  45. path.append((i,j))
  46. paths[(i,j)] = (path,elevation_sofar+elevation-last_elevation,elevation)
  47. for ii,jj in higher_neighbours:
  48. update_paths(paths,arr,ii,jj)
  49.  
  50. def solve(arr,paths):
  51. for i,row in enumerate(arr):
  52. for j,point in enumerate(row):
  53. update_paths(paths,arr,i,j)
  54.  
  55. def get_array_from_file(f):
  56. a = []
  57. row,col = map(int,f.readline().split())
  58. i = 0 ;
  59. while i < row:
  60. a.append(map(int,f.readline().split()))
  61. i=i+1
  62. return a
  63.  
  64. if __name__ == '__main__':
  65. paths = {}
  66. f = None
  67. if len(sys.argv) == 1:
  68. f = sys.stdin
  69. else:
  70. f = open(sys.argv[1],"r")
  71. arr = get_array_from_file(f)
  72. solve(arr,paths)
  73. print reduce(get_max,paths.values())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement