题目描述
You have a long drive by car ahead. You have a tape recorder, but unfortunately your best music is on CDs. You need to have it on tapes so the problem to solve is: you have a tape N minutes long. How to choose tracks from CD to get most out of tape space and have as short unused space as possible. Assumptions:
• number of tracks on the CD does not exceed 20
• no track is longer than N minutes
• tracks do not repeat
• length of each track is expressed as an integer number
• N is also integer
Program should find the set of tracks which fills the tape best and print it in the same sequence as the tracks are stored on the CD
Input
Any number of lines. Each one contains value N, (after space) number of tracks and durations of the tracks. For example from first line in sample data: N = 5, number of tracks=3, first track lasts for 1 minute, second one 3 minutes, next one 4 minutes
Output
Set of tracks (and durations) which are the correct solutions and string ‘sum:’ and sum of duration times.
Sample Input
5 3 1 3 4
10 4 9 8 4 2
20 4 10 5 7 4
90 8 10 23 1 2 3 4 5 7
45 8 4 10 44 43 12 9 8 2
Sample Output
1 4 sum:5
8 2 sum:10
10 5 4 sum:19
10 23 1 2 3 4 5 7 sum:55
参考思路
什么?你说看不懂题目。好吧,其实我也看不懂(
不是)这题就是01背包求方案数,sum其实就是最大价值,N就是限制的重量。
如何求方案呢?
首先,我们可以从后往前遍历物品,让最优解落在dp[1][N]中,然后我们从f[1][N]开始搜索方案。
状态定义:dp[i][j]表示从第i个物品到最后一个物品装入容量为j的背包的最优解。
状态转移:dp[i][j] = max(dp[i + 1][j], dp[i + 1][j - a[i]] + a[i]) 上一个物品我们选或者不选两者的最大价值
我们开始求方案数的时候,会面临三种情况
- 如果dp[i][j]=dp[i + 1][j];不选第i个物品才可以得到最优解。
- 如果dp[i][j]=dp[i + 1][j - a[i]] + a[i];选第i个物品才可以得到最优解。
- 当dp[i + 1][j]=dp[i + 1][j - a[i]] + a[i];我们为了方便(可以说字典序最小),我们选第该物品
举例
4 7 这里举背包问题的例子 4代表四个背包 7是最大容量
1 1 重量 价值
2 3
3 4
4 5
演示过程
参考代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<sstream>
#include<string>
#include<map>
using namespace std;
typedef long long ll;
#define F 10005
int a[F], dp[F][F];
int N, n;
int main()
{
while (scanf("%d",&N) != EOF)
{
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
for(int i=n;i>=1;--i)//开始逆推 让答案落在dp[1][N]上
for (int j = 0; j <= N; ++j)
{
if (j >= a[i])
dp[i][j] = max(dp[i + 1][j], dp[i + 1][j - a[i]] + a[i]);
else
dp[i][j] = dp[i + 1][j];
}
int j = N;//剩余容量
for (int i = 1; i <= n; ++i)//找路
{
if (j >= a[i] && dp[i][j] == dp[i + 1][j - a[i]] + a[i])//只要符合就输出
{
cout << a[i] << " ";
j -= a[i];//选了第i个物品,容量减少
}
}
cout <<"sum:" << dp[1][N] << endl;
//memset(dp, 0, sizeof(0));
for (int i = 0; i <= n; ++i)//这里建议手动重置数组
for (int j = 0; j <= N; ++j)
dp[i][j] = 0;
}
return 0;
}
如果有更好的方法或者有错误的地方,欢迎斧正。
感谢您的阅读!(*^▽^*)