SDUN上部分背包问题及解析

1.首先是1033这道题
纯纯正正赤赤裸裸的01背包问题
做这种问题时,设ly是利益,设zl是限制条件,有n个东西,限制的最大条件w;
下面是思路

int b,c;
int a=[w+1];   //a[x] 表示背包容量为x 时的最大价值  
for ( b=0; b<n; b++)  
    for ( c=w; c>=zl[i]; c--)  
    if(a[c]<a[c-zl[i]]+li[i])
        a[c]=a[c-zl[i]]+li[i];

贴代码

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    int a, b, c, d, e, f;
    scanf("%d %d", &a, &b);
    int t[101], j[101], s[1001] = {0};
    for (c = 1; c <= b; c++)
    {
        scanf("%d %d", &t[c], &j[c]);
    }
    for (c = b; c >0; c--)
    {
        for (d = a; d >=t[c]; d--)
        {
            if (s[d] < s[d - t[c]] + j[c])
            {
                s[d] = s[d - t[c]] + j[c];
            }
        }
    }
    printf("%d\n", s[a]);
    return 0;
}

2.完全背包问题
例如1360这道题
其实差不多思路,就是改改循环顺序;
做这种问题时,设ly是利益,设zl是限制条件,有n个东西,限制的最大条件w;
下面是思路

int b,c;
int a=[w+1];   //a[x] 表示背包容量为x 时的最大价值  
for ( b=0; b<n; b++)  
    for ( c=zl[i]; c<=w; c++)  
    if(a[c]<a[c-zl[i]]+li[i])
        a[c]=a[c-zl[i]]+li[i];

1360
贴代码

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    int a, b, c, d, e, f;
    int r[101], x[101];
    while (cin >> a)
    {
        int m[100000] = { 0 };
        for (b = 1; b <= a; b++)
        {
            cin >> x[b] >> r[b];
        }
        cin >> d;
        for (c = 1; c <= a; c++)
        {
            for (e = r[c]; e <= d; e++)
            {
                if (m[e] < m[e - r[c]] + x[c])
                {
                    m[e] = m[e - r[c]] + x[c];
                }
            }
        }
        printf("%d\n", m[d]);
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值