如何花最少的钱购买蔬菜
Description
Rahul wanted to purchase vegetables mainly brinjal, carrot and tomato. There are N different vegetable sellers in a line. Each vegetable seller sells all three vegetable items, but at different prices. Rahul, obsessed by his nature to spend optimally, decided not to purchase same vegetable from adjacent shops. Also, Rahul will purchase exactly one type of vegetable item (only 1 kg) from one shop. Rahul wishes to spend minimum money buying vegetables using this strategy. Help Rahul determine the minimum money he will spend.
Input
First line indicates number of test cases T. Each test case in its first line contains N denoting the number of vegetable sellers in Vegetable Market. Then each of next N lines contains three space separated integers denoting cost of brinjal, carrot and tomato per kg with that particular vegetable seller.
Output
For each test case, output the minimum cost of shopping taking the mentioned conditions into account in a separate line.
Constraints:1 <= T <= 10,1 <= N <= 100000 Cost of each vegetable(brinjal/carrot/tomato) per kg does not exceed 10^4
Sample Input 1
1
3
1 50 50
50 50 50
1 50 50
Sample Output 1
52
分析
python3
# 花最少的钱买蔬菜
# 用动态规划,构建dp数组,最后一行的最小值就是所求结果
if __name__ == '__main__':
for _ in range(int(input())):
num_shop = int(input())
arr = []
for _ in range(num_shop):
arr.append(list(map(int, input().split())))
num_vege = 3
# 构建dp数组
dp = [[0] * num_vege for _ in range(num_shop)]
for i in range(num_vege): # 初始化dp数组首行
dp[0][i] = arr[0][i]
for i in range(1, num_shop):
for j in range(num_vege): # j==1时,找j=2,j=0 j==2时,找j=0,j=1
dp[i][j] = min(dp[i-1][(j+1)%3], dp[i-1][(j+2)%3]) + arr[i][j]
print(min(dp[-1]))