1119. 背包问题1

版权声明:本博客的博文版权为2018韦泽鑫所有,复制文章转载时记得附上本博客的地址哦 https://blog.csdn.net/qq_40167327/article/details/81025413

题目链接:背包问题1

题目描述:

有个背包可承受重量N,现有T件物品
每件物品重量为Wi,价值为Vi ,每件物品只有一个,

这个背包可以装载物品的最大价值是多少?

输入:

一行,N T 之间用空格隔开

后面t行,每行:重量Wi,价值Vi

输出:

这个背包可以装载物品的最大价值

样例输入:

100 5
77 92
22 22
29 87
50 46
99 90

样例输出:

133

题解思路:

这道题是01背包,每个物品只有一个,可以用堆积木的方式做一次从背包最大容量到0的for循环,只要这一层有物品到达,就比较价值就好了。上代码: 

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int n,t,f[100005],x=-999999999;
struct nod{int a,b;}d[100005];
int main()
{
    cin>>n>>t;
    for(int i=1;i<=t;i++)
    {
        cin>>d[i].a>>d[i].b;
    }
    f[0]=0;
    for(int i=1;i<=t;i++)
    {
        for(int j=n-d[i].a;j>=0;j--)
        {
            if(f[j]!=0||j==0)
            {
                if(f[j+d[i].a]!=0)
                {
                    if(f[j]+d[i].b>f[j+d[i].a])
                    {
                        f[j+d[i].a]=f[j]+d[i].b;
                    }
                }
                else
                {
                    f[j+d[i].a]=f[j]+d[i].b;
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        if(f[i]>x)
        {
            x=f[i];
        }
    }
    cout<<x;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_40167327/article/details/81025413