题面
东东开车出去泡妞(在梦中),车内提供了 n 张CD唱片,已知东东开车的时间是 n 分钟,他该如何去选择唱片去消磨这无聊的时间呢
假设:
CD数量不超过20张
没有一张CD唱片超过 N 分钟
每张唱片只能听一次
唱片的播放长度为整数
N 也是整数
我们需要找到最能消磨时间的唱片数量,并按使用顺序输出答案(必须是听完唱片,不能有唱片没听完却到了下车时间的情况发生)
本题是 Special Judge
Input
多组输入
每行输入第一个数字N, 代表总时间,第二个数字 M 代表有 M 张唱片,后面紧跟 M 个数字,代表每张唱片的时长 例如样例一: N=5, M=3, 第一张唱片为 1 分钟, 第二张唱片 3 分钟, 第三张 4 分钟
所有数据均满足以下条件:
N≤10000
M≤20
Output
输出所有唱片的时长和总时长,具体输出格式见样例
Sample
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
4 10 12 9 8 2 sum:45
题解
本题要输出01背包的路径,这样的话需要二维数组记录过程:p[i][j]表示j容量的最优解是否选取了第i个物品,之后再递归到j-a[i]的容量是否选取了第i-1个物品…
代码
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<set>
using namespace std;
#define rep(i,s,t) for(int i=s;i<=t;i++)
#define mem(a,s) memset(a,s,sizeof(a))
typedef long long LL;
const int M=1e4+10;
const int N=20+5;
int dp[M];
int p[N][M];
int a[N];
int n, L;
void output(int i,int l){
if(i>1)
output(i - 1, l - p[i][l]);
if(p[i][l])
cout << p[i][l] << ' ';
}
int main(){
// freopen("in.txt","r",stdin);
while(cin>>L){
mem(dp, 0);mem(p, 0);
cin >> n;
rep(i, 1, n)
cin >>a[i];
rep(i, 1, n)
for (int j = L; j >= a[i];j--)
if(dp[j]<=dp[j-a[i]]+a[i]){
dp[j] = dp[j - a[i]] + a[i];
p[i][j] = a[i];
}
output(n,L);
cout << "sum:" << dp[L] << endl;
}
return 0;
}