题目:
辰辰是个天资聪颖的孩子,他的梦想是成为世界上最伟大的医师。为此,他想拜附近最有威望的医师为师。医师为了判断他的资质,给他出了一个难题。医师把他带到一个到处都是草药的山洞里对他说:“孩子,这个山洞里有一些不同的草药,采每一株都需要一些时间,每一株也有它自身的价值。我会给你一段时间,在这段时间里,你可以采到一些草药。如果你是一个聪明的孩子,你应该可以让采到的草药的总价值最大。”
如果你是辰辰,你能完成这个任务吗?
输入格式
第一行有两个整数 TT(1 \le T \le 10001≤T≤1000)和 MM(1 \le M \le 1001≤M≤100),用一个空格隔开,T代表总共能够用来采药的时间,MM 代表山洞里的草药的数目。
接下来的 MM 行每行包括两个在 11 到 100100 之间(包括 11 和 100100 )的整数,分别表示采摘某株草药的时间和这株草药的价值。
输出格式
包括一行,这一行只包含一个整数,表示在规定的时间内,可以采到的草药的最大总价值。
数据范围
对于 30\%30% 的数据,M \le 10M≤10;
对于全部的数据, M \le 100M≤100。
样例1输入:
70 3
71 100
69 1
1 2
样例1输出:
3
题解:这道题是很经典的背包问题。这里来说一说节省空间的背包问题的做法吧。
先丢一段经典的背包问题做法代码
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
int c,b[1001][1001]={},m,t,a;
//b[i][j]中的i是指第i棵药,j是指第j点体力
cin >> t >> m;
for (int i=1;i<=m;i++)
{
cin >> a >> c;
for (int j=1;j<=t;j++)
if (j>=a) b[i][j]=max(b[i-1][j-a]+c,b[i-1][j]);//当能采集当前药时进行比较,是摘这颗药好还是不摘好,b记录的是最佳价值
else b[i][j]=b[i-1][j]; //不能采集时与上一层相同
}
cout << b[m][t];
}
然后我们发现,b数组只与b[i-1]层有关,那我们用滚动数组,即可省下很大空间。
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
int c,b[3][1001]={},m,t,a,what;
cin >> t >> m;
what=1;
for (int i=1;i<=m;i++)
{
what=!what;//what滚动
cin >> a >> c;
for (int j=1;j<=t;j++)
if (j>=a) b[what][j]=max(b[!what][j-a]+c,b[!what][j]);
else b[what][j]=b[!what][j];
}
cout << b[what][t];
}
再细看,发现只要体力从后往前判断,就可以用一层数组来解决。(不会覆盖掉仍然要用的数据)
b[j]是变更的j体力时的最佳,b[j-a]却是上一层的最佳值。
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
int c,b[1001]={},m,t,a,what;
cin >> t >> m;
what=1;
for (int i=1;i<=m;i++)
{
cin >> a >> c;
for (int j=t;j>=a;j--)//从后往前判断
b[j]=max(b[j],b[j-a]+c);
}
cout << b[t];
}
但是注意节省空间之后就不能找回我们取了哪几棵药