首页 > 代码库 > hdu2546_01背包+贪心

hdu2546_01背包+贪心

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2546

注意:m<5的情况。。。

代码:

#include<cstdio>#include<iostream>#include<cstring>#include<cstdlib>#include<algorithm>using namespace std;const int maxn = 1e3+10;int dp[maxn][maxn];int a[maxn];int main() {    //freopen("test.txt", "r", stdin);    int n, m;    while(scanf("%d", &n)!=EOF) {        if(n==0) break;        for(int i=1; i<=n; i++)            scanf("%d", &a[i]);        scanf("%d", &m);        if(m<5) {            printf("%d\n", m);            continue;        }        m = m-5;        sort(a+1, a+n+1);        for(int i=0; i<=n; i++) {            dp[0][i] = 0;        }        for(int i=1; i<n; i++) {            for(int j=0; j<=m; j++) {                if(j>=a[i]) { // buy or not                    dp[i][j] = max(dp[i-1][j-a[i]]+a[i], dp[i-1][j]);                }                else dp[i][j] = dp[i-1][j];            }        }        printf("%d\n", m-dp[n-1][m]-a[n]+5);    }    return 0;}
View Code

 

hdu2546_01背包+贪心