2023.4.1 美团笔试
第一题
给出一个加号连接的操作序列,使用加减乘除随机替换其中一个加号,求修改之后的结果。
这个题Python只过了18%的点,只要求一位小数感觉也不是精度问题。有点奇怪。
n = int(input())
a = list(map(float, input().split(" ")))
m = int(input())
ops = input().split(" ")
assert len(ops) == 2*m
sum_a = sum(a)
ans = []
for i in range(m):
idx, op = int(ops[2*i]), ops[2*i+1]
tmp = float(eval(f"{a[idx-1]}{op}{a[idx]}") - a[idx-1] - a[idx])
if op == "+":
tmp = a[idx-1] + a[idx] - a[idx-1] - a[idx]
if op == "-":
tmp = a[idx-1] - a[idx] - a[idx-1] - a[idx]
if op == "*":
tmp = a[idx-1] * a[idx] - a[idx-1] - a[idx]
if op == "/":
tmp = a[idx-1] / a[idx] - a[idx-1] - a[idx]
ans.append(f"{(sum_a + tmp):.1f}")
print(" ".join(ans))
第二题
第二题求一个数组任意排序之后,求最小的相邻两数的差的和,排序即可。AC
n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
# print(a)
ans = 0
for i in range(n-1):
ans += a[i+1]-a[i]
print(ans)
第三题
树状数字板子题,单点更新,区间求和。AC
class BinTree:
def __init__(self, n):
self.l = [0] * (n + 1)
self.n = n
def lowbit(self, x):
return x & -x
def add(self, x, y):
while x <= n:
self.l[x] += y
x += self.lowbit(x)
def cal(self, x):
ans = 0
while x > 0:
ans += self.l[x]
x -= self.lowbit(x)
return ans
n, m = list(map(int, input().split()))
op = list(map(int, input().split()))
x = list(map(int, input().split()))
y = list(map(int, input().split()))
# print(n, m)
# print(op)
# print(x)
# print(y)
tree = BinTree(n)
ans = []
for i in range(m):
# print(op[i], x[i], y[i])
if op[i] == 1:
ans.append(str(tree.cal(y[i]) - tree.cal(x[i]-1)))
else:
cur = tree.cal(x[i]) - tree.cal(x[i]-1)
tree.add(x[i], y[i] - cur)
print(" ".join(ans))
第四题
倒水🫗题,题有点长不写了,看代码吧。AC
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
z = list(map(int, input().split()))
ans = [0] * n
for i in range(n-1, -1, -1):
cnt = 0
tmp = 10**18
for j in range(i, -1, -1):
cnt += x[j] - y[j]
tmp = min(tmp, z[j] * cnt)
ans[i] = tmp
m = int(input())
q = list(map(int, input().split()))
for i in range(m):
print(ans[q[i]-1], sep=" ")
