阿里8.27 笔试 Python代码
1. 给定数组nums,执行k次操作,每次选择一个数+1,求k次之后可能最小的全组最大数。
n, k = map(int,input().split()) nums = list(map(int, input().split())) maxn = max(nums) total = sum(nums)+k if total%n == 0: print(max(total//n,maxn)) else: print(max(total//n+1, maxn))
2.给定grid,'0'表示可通过,'1'表示不可通过,在[x,y]处有军队(多处),求所有军队集合的最短时间,不能集合返回-1。
n, m = map(int, input().split()) grid = [] for i in range(n): row = list(input().strip('')) grid.append(row) k = int(input()) cord = [] for j in range(k): x,y = map(int,input().split()) cord.append([x-1,y-1]) dirs = [[0,-1],[0,1],[-1,0],[1,0]] def neibors(i,j,visited,grid): res = [] for dx,dy in dirs: x = i+ dx y = j+ dy if x in range(n) and y in range(m) and not visited[x][y] and grid[x][y] != '1': res.append([x,y]) return res def dfs(grid, x, y, cur, visited, new): new[x][y] = cur visited[x][y] = True neibor = neibors(x,y,visited,grid) if len(neibor) > 0: for i,j in neibor: dfs(grid, i, j, cur+1, visited, new) return new def update(m1,m2): for i in range(n): for j in range(m): m1[i][j] = max(m1[i][j], m2[i][j]) return m1 result = [[0]*m for _ in range(n)] for x,y in cord: new = [[10**10]*m for _ in range(n)] visited = [[False]*m for _ in range(n)] this = dfs(grid, x, y, 0, visited, new) result = update(result, this) curmin = 10**10 for i in range(n): for j in range(m): curmin = min(curmin, result[i][j]) if curmin != 10**10: print(curmin) else: print(-1)
测试例子
3 3 000 101 000 4 1 1 1 3 3 1 3 3