其他分享
首页 > 其他分享> > 疯狂的采药(完全背包)

疯狂的采药(完全背包)

作者:互联网

疯狂的采药

题目链接:https://www.luogu.com.cn/problem/P1616
核心代码:

for(int i=1;i<=m;i++)
	{
		for(int j=weight[i];j<=n;j++)
		{
			dp[j]=max(dp[j],dp[j-weight[i]]+value[i]);
		}
	}

完全背包(每种物品有无限件可以用)代码和01背包很像,但要注意01背包内层循环是逆序,而完全背包则是顺序进行!
此处附上01背包代码进行对比。( m m m和 n n n看题,此处无关。)

for(int i=1;i<=n;i++)
		{
			for(int j=m;j>=weight[i];j--)
			{
				f[j]=max(f[j],f[j-weight[i]]+value[i]);
			}
	}	

疯狂的采药题解
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#define int long long
using namespace std;
int dp[10000010];
int weight[10000010];
int value[10000010];
signed main()
{
	int n,m,k,s; 
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		scanf("%lld %lld",&weight[i],&value[i]);
	}
	for(int i=1;i<=m;i++)
	{
		for(int j=weight[i];j<=n;j++)
		{
			dp[j]=max(dp[j],dp[j-weight[i]]+value[i]);
		}
	}
	cout<<dp[n]<<endl;
}

标签:背包,weight,int,疯狂,value,采药,include,dp
来源: https://blog.csdn.net/qizhiqiqwq/article/details/115435179