poj 3624 01背包

题意:01背包经典问题。

思路:动态规划。01背包使用一个一位数组即可,此时更新必须从右向左。

输入:

4 6
1 4
2 6
3 12
2 7

输出:

23

#include <stdio.h>
#include <string.h>
#define N 3402
#define M 12885
int w[N],v[N];
int dp[M];
int n,m;//m为背包的最大容量,n为物品的种类数
int max(int a,int b){
	if(a>b)
		return a;
	return b;
}
int main(){
	freopen("a.txt","r",stdin);
	while(scanf("%d %d",&n,&m)!=EOF){
		int i,j;
		memset(dp,0,sizeof(dp));
		for(i = 0;i<n;i++)
			scanf("%d %d",&w[i],&v[i]);
		for(i = 0;i<n;i++)
			for(j = m;j>=w[i];j--)
				dp[j] = max(dp[j],dp[j-w[i]]+v[i]);
		printf("%d\n",dp[m]);
	}
	return 0;
}

python版本:
def Max(a,b):
    if a>b:
        return a
    return b

w = []
v = []
dp = []
i = j = 0
    
fp = open("a.txt")
buf = fp.readline()
(n,m) = buf.split()
n = int(n)
m = int(m)
for i in range(0,m+1):
    dp.append(0)
    
for buf in fp:
    (i,j) = buf.split()
    w.append(int(i))
    v.append(int(j))

for i in range(0,n):
    for j in range(m,w[i]-1,-1):
        dp[j] = Max(dp[j],dp[j-w[i]]+v[i]);

print(dp[m])


你可能感兴趣的:(poj 3624 01背包)