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
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
Set of tracks (and durations) which are the correct solutions and string ‘sum:’ and sum of duration
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
1 4 sum:5
8 2 sum:10
10 5 4 sum:19
10 23 1 2 3 4 5 7 sum:55
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
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
Set of tracks (and durations) which are the correct solutions and string ‘sum:’ and sum of duration
times.
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
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背包二维数组的动态转移方程dp[i][j]=max(dp[i-1][j],dp[i-1][j-v[i]]+w[i]),可以知道,dp[i][j]的状态和dp[i-1][j]、dp[i-1][j-v[i]]有关,于是,在记录路径的时候,要是dp[i][j]==dp[i-1][j],说明,这条路没有走向dp[i-1][j-v[i]],这时,可以另开一个数组a[i][j],当dp[i][j]在动态转移时,==dp[i-1][j],则a[i][j]=0,否则a[i][j]=1;然后对数组a[i][j]进行回溯即可
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define max(x,y) (x>y? x:y)
int dp[13000],a[1000][1000],w[13000],f[10000],count=0;
void print(int n,int m)
{
if(n==0)
return;
if(a[n][m]==0)
print(n-1,m);
else
{
print(n-1,m-w[n]);
f[count++]=w[n];
}
}
int main()
{
int n,m;
while(scanf("%d%d",&m,&n)>0)
{
int i;
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
memset(dp,0,sizeof(dp));
memset(a,0,sizeof(a));
a[0][0]=1;
for(i=1;i<=n;i++)
{
for(int j=m;j>=w[i];j--)
{
dp[j]=max(dp[j],dp[j-w[i]]+w[i]);
if(dp[j]==dp[j-w[i]]+w[i])
a[i][j]=1;
}
}
count=0;
print(n,m);
for(i=0;i<count;i++)
{
printf("%d ",f[i]);
}
printf("sum:%d\n",dp[m]);
}
return 0;
}