RT。职务地址http://zju.acmclub.com/index.php?app=problem_title&id=1&problem_id=2123
ps:(1)01背包和全然背包的差别在于计算方向,01背包的计算顺序是从上往下,从右往左;全然背包则是从上往下,从左往右
(2)背包是否装满的差别在于初始化第0行,若不一定装满则所有初始化为0,
若要求必须装满则dp[0]=0,dp[1~C]=(求最小值时初始化为INF,求最大值时初始化为-INF)
(3)终于返回的dp[C]即为结果。
python代码:
#coding=utf-8 INF = 1000000 def Matrix(rows,cols): #matrix = [[0 for col in range(cols)] for row in range(rows)] matrix = [0 for col in range(cols)] return matrix t = input() while t: [x,y]=raw_input().split() C=int(y)-int(x) lines=input() n = lines weight = [] price = [] while lines: [a,b]=raw_input().split() weight.append(int(b)) price.append(int(a)) lines -= 1 if lines==0:break mat = Matrix(n+1,C+1) #init row-0 in matrix mat[0]=0 for j in range(1,C+1):mat[j]=INF #compute the matrix for i in range(1,n+1): for j in range(weight[i-1],C+1): mat[j]=min(mat[j],mat[j-weight[i-1]]+price[i-1]) if mat[C]==INF:print "This is impossible." else: print "The minimum amount of money in the piggy-bank is %d." % mat[C] t -= 1 if t==0:break
版权声明:本文博主原创文章。博客,未经同意不得转载。
时间: 2024-11-05 11:54:47