简单的01背包问题
http://acm.hdu.edu.cn/showproblem.php?pid=2546
#include "HDU2546.h"
#include<iostream>
#include<algorithm>
using namespace std;
int cmp(int a, int b){
return a < b;
}
int main(){
int n;
while (scanf("%d", &n), n)
{
int price[2013]={0};
int dp[2013]={0};
for(int i = 1; i <= n; i++)
scanf("%d", &price[i]);
sort(price + 1, price + 1 + n);
int MAX = price[n];
int m;
scanf("%d", &m);
if (m < 5)
{
printf("%d\n",m);
continue;
}
m -= 5;
for (int i = 1; i < n; i++)
{
for (int j = m; j >= price[i]; j--)
{
dp[j] = max(dp[j], dp[j-price[i]] + price[i]);
}
}
printf("%d\n", m+5-dp[m]-MAX);
}
return 0;
}
HDU2546::HDU2546(void)
{
}
HDU2546::~HDU2546(void)
{
}
几个注意点:
1.两个数组的初始值都为零,原先把DP[],price[] 都设置成全局变量,导致了wrong answer,低级错误~~
2.对于数组下标犯错了
3. m的值刚开始没有减 5