腾讯 算法岗 10.16笔试
这笔试懂得都懂hhhh 不过正好没事,随缘参加一下,总体还是偏简单了点,全是模拟排序,就T5是一个树形DP
Q1
t = int(input()) def solve(): x, y, k = map(int, input().split()) def gcd(a, b): while a: a, b = b % a, a return b res = 1 for i in range(k + 1): tmp = gcd(x + i, y + k - i) res = max(res, tmp) return res for _ in range(t): print(solve())
Q2
t = int(input()) def solve(): n, m, t = input().split() n = int(n) m = int(m) t = float(t) x = list(map(float, input().split())) mat1 = [] mat2 = [] for _ in range(m): tmp = list(map(float, input().split())) mat1.append(tmp) for _ in range(m): tmp = list(map(float, input().split())) mat2.append(tmp) def matmul(a, b): # a 1 * n # b n * m res = [0] * m for i in range(m): tmp = 0 for j in range(n): tmp += a[j] * b[i][j] res[i] = tmp return res f = matmul(x, mat1) g = matmul(x, mat2) acc = 0 for i in range(m): acc += (f[i] - g[i]) ** 2 if acc > t ** 2: return 1 else: return 0 for _ in range(t): print(solve())
Q3
def solve(): n = int(input()) x = [] y = [] points = [] for _ in range(n): a, b = map(int, input().split()) x.append(a) y.append(b) points.append([a,b]) x.sort() if x[n // 2] - x[n // 2 - 1] <= 1: return print(-1) b = x[n // 2 - 1] + 1 l = [] r = [] for x1, y1 in points: if x1 < b: l.append(y1) else: r.append(y1) l.sort() r.sort() if l[n // 4] - l[n // 4 - 1] <= 1: return print(-1) if r[n // 4] - r[n // 4 - 1] <= 1: return print(-1) left = max(l[n // 4 - 1] + 1, r[n // 4 - 1] + 1) right = min(l[n // 4] - 1, r[n // 4] -1) if left > right: return print(-1) return print(right, b) solve()
Q4
n = int(input()) def solve(): loc = [] speed = [] for _ in range(n): x, v = map(int, input().split()) loc.append(x) speed.append(v) loc.sort() speed = [[s, i] for i, s in enumerate(speed)] speed.sort() res = [[-1,-1] for _ in range(n)] for i in range(n): res[speed[i][-1]] = [loc[i], speed[i][0]] for a, b in res: print(a, b) solve()
Q5
思路:树形dp,自底向上,到当前节点p的时候 需要考虑是否有两个子节点相加最大,往上传的参数为p的权重与子节点加路径的最大值,详情见代码
def solve(): n = int(input()) *weights, = map(int, input().split()) from collections import defaultdict g = defaultdict(list) for _ in range(n - 1): x, y, d = map(int, input().split()) g[x - 1].append((y - 1, d)) g[y - 1].append((x - 1, d)) res = 0 def dfs(node, fa): nonlocal res first = -1 second = -1 for new, d in g[node]: if new == fa: continue tmp = dfs(new, node) + d if tmp > first: second = first first = tmp elif tmp > second: second = tmp if first == -1: res = max(res, weights[node]) return weights[node] # 两个节点 if second != -1: res = max(res, first + second) # 当前node节点 res = max(res, weights[node] + first) # 最后的节点可能就到node,所以要取max return max(first, weights[node]) dfs(0,-1) return res print(solve())#腾讯笔试##秋招笔试##秋招#