题目来源:牛客,阿里巴巴编程题(2星),第7题
题目描述
题解
法一:错误方法🙅♂️
想用贪心去解,但解法是错的,代码如下:
def main():
n = int(input())
a1 = [int(i) for i in input().split()]
a2 = [int(i) for i in input().split()]
a3 = [int(i) for i in input().split()]
l1 = [a1[0],a2[0],a3[0]]
l2 = [a1[1],a2[1],a3[1]]
ans,st=1e9,0
for j in range(3):
for k in range(3):
if abs(l1[j]-l2[k])<ans:
ans = abs(l1[j]-l2[k])
st = l2[k]
for i in range(2,n):
tmp = min([abs(st-ai) for ai in [a1[i],a2[i],a3[i]]])
ans += tmp
st = a1[i] if abs(st-a1[i])==tmp else a2[i] if abs(st-a2[i])==tmp else a3[i]
print(ans)
return
if __name__ == '__main__':
main()
法二:动态规划🙆♂️
这算是比较经典的动态规划题,但我竟然第一时间没往这方面想,还是得多练
动态规划的关键在于定义dp数组。这里,子问题是选择下一个使绝对值总和最小的值。但解决问题的时候反过来看,对于待选择的三个值,他们加上之前的那一组之和能够最小。最终,再从这三个值中选取最小值,这样一定能保证最优解。
def main():
n = int(input())
matrix = []
for k in range(3):
matrix.append([int(i) for i in input().split()])
dp_matrix = [[0,0,0]]
for i in range(1,n):
d0 = min([abs(matrix[j][i-1]-matrix[0][i])+dp_matrix[i-1][j] for j in range(3)])
d1 = min([abs(matrix[j][i-1]-matrix[1][i])+dp_matrix[i-1][j] for j in range(3)])
d2 = min([abs(matrix[j][i-1]-matrix[2][i])+dp_matrix[i-1][j] for j in range(3)])
dp_matrix.append([d0,d1,d2])
print(min(dp_matrix[-1]))
return
if __name__ == '__main__':
main()