hdu1248 寒冰王座(完全背包)

来源:互联网 发布:中国网络域名注册 编辑:程序博客网 时间:2024/06/02 07:31

本题可以用完全背包做,但感觉背包就是大材小用。背包是指不同大小和价值的物品放入固定容量背包所得的最大价值,注意有两个变量。而本题只是衡量价值。为一个变量,所以暴力也可以。

暴力法:

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int N = 1005;int main(){  //  freopen("in.txt", "r", stdin);    int T, i, j, k, n, num, maxx, a, b, c;    scanf("%d", &T);    while(T --)    {        scanf("%d", &n);        a = n / 150;        b = n / 200;        c = n / 350;        maxx = 0;        for(i = 0; i <= a; i ++)            for(j = 0; j <= b; j ++)                for(k = 0; k <= c; k ++)                {                    num = i * 150 + j * 200 + k * 350;                    if(num <= n) maxx = max(maxx, num);                }        printf("%d\n", n - maxx);    }    return 0;}


背包法:

把两个数组合并成一个即可,既然已给出物品价格,所以打表,最后第一个for遍历3次即可。注意数组开小现实的是超时而不是WA。

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int N = 10005;int main(){  //  freopen("in.txt", "r", stdin);    int T, i, j, n, ans[N];    int val[3] = {150, 200, 350};    scanf("%d", &T);    while(T --)    {        scanf("%d", &n);        memset(ans, 0, sizeof(ans));        for(i = 0; i < 3; i ++)            for(j = val[i]; j <= n; j ++)                ans[j] = max(ans[j], ans[j - val[i]] + val[i]);        printf("%d\n", n - ans[n]);    }    return 0;}


0 0
原创粉丝点击