https://www.hackerrank.com/challenges/two-robots/problem
思路:DP。用dp[i][j][k]表示执行到第i步,一个在j位置,一个在k位置,复杂度O(NNK),TLE
其实有一个robot一定停在当前query的结束位置,只需要枚举另外一个robot(可以是2个robot交替着来)的位置就好了,复杂度O(NK)
def twoRobots(m, queries):
n=len(queries)
dp=[[[float('inf') for _ in range(m+1)] for _ in range(m+1)] for _ in range(n+1)]
dp[0]=[[0 for _ in range(m+1)] for _ in range(m+1)]
for i in range(1,n+1):
s,t=queries[i-1]
for j in range(1,m+1):
for k in range(1,m+1):
dp[i][t][k]=min(dp[i][t][k], dp[i-1][j][k]+abs(j-s)+abs(s-t))
dp[i][j][t]=min(dp[i][j][t], dp[i-1][j][k]+abs(k-s)+abs(s-t))
return min(t for t in min(dp[n]))
print(twoRobots(10, [[2,4],[5,4],[9,8]]))
def twoRobots(m, queries):
n=len(queries)
dp=[[float('inf') for _ in range(m+1)] for _ in range(n)]
dp[0]=[abs(queries[0][1]-queries[0][0]) for _ in range(m+1)]
for i in range(n-1):
_,t0=queries[i]
s,t=queries[i+1]
for j in range(1,m+1):
dp[i+1][j]=min(dp[i+1][j], dp[i][j]+abs(t0-s)+abs(s-t))
dp[i+1][t0]=min(dp[i+1][t0], dp[i][j]+abs(j-s)+abs(s-t))
return min(dp[n-1])
print(twoRobots(10, [[2,4],[5,4],[9,8]]))