1.题意
东东开车出去泡妞(在梦中),车内提供了 n 张CD唱片,已知东东开车的时间是 n 分钟,他该如何去选择唱片去消磨这无聊的时间呢
假设:
CD数量不超过20张
没有一张CD唱片超过 N 分钟
每张唱片只能听一次
唱片的播放长度为整数
N 也是整数
我们需要找到最能消磨时间的唱片数量,并按使用顺序输出答案(必须是听完唱片,不能有唱片没听完却到了下车时间的情况发生)
2.样例
Input
多组输入
每行输入第一个数字N, 代表总时间,第二个数字 M 代表有 M 张唱片,后面紧跟 M 个数字,代表每张唱片的时长 例如样例一: N=5, M=3, 第一张唱片为 1 分钟, 第二张唱片 3 分钟, 第三张 4 分钟
所有数据均满足以下条件:
N≤10000
M≤20
Output
输出所有唱片的时长和总时长,具体输出格式见样例
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
3.解题思路
- 该题是在0、1背包上的变形,要求记录路径,用ff[i][j]表示当前的f[i][j]选了第i个物品
- 对于超时问题,将ff数组第一维开小些
4.AC代码
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;
const int M=1e4+5;
int n,m;
int tk[25]={0};
int f[M]={0};
int ff[25][M]={0};
//vector<int>v;
int v[M]={0};
int main()
{
while(~scanf("%d",&n))
{
//cin>>m;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
//cin>>tk[i];
scanf("%d",&tk[i]);
}
memset(f,0,sizeof(f));
memset(ff,0,sizeof(ff));
//v.clear();
for(int i=1;i<=m;i++)
{
for(int j=n;j>=tk[i];j--)
{
if(f[j]<f[j-tk[i]]+tk[i])
{
f[j]=f[j-tk[i]]+tk[i];
ff[i][j]=1;
}
}
}
int cnt=0;
for(int i=m,j=n;i>=1&&j>=0;i--)
{
if(ff[i][j]==1)
{
j=j-tk[i];
//v.push_back(tk[i]);
v[cnt]=tk[i];
cnt++;
}
}
for(int i=cnt-1;i>=0;i--)
{
//cout<<v[i]<<" ";
printf("%d ",v[i]);
}
//cout<<"sum:"<<f[n]<<endl;
printf("sum:%d\n",f[n]);
}
return 0;
}