You have a long drive by car ahead. You have a tape recorder, but unfortunatelyyour best music is on CDs. You need to have it on tapes so the problem to solveis: you have a tape N minutes long. How to choose tracks from CD to get most outof 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 itin the same sequence as the tracks are stored on the CD
Any number of lines. Each one contains value N, (after space) number of tracksand 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, nextone 4 minutes
Set of tracks (and durations) which are the correct solutions andstring ``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
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[30][10000];
int path[100];
int a[30];
int vis[40];
int n,m;
int flag=0;
void print(int x,int y)
{
if(y<0||x<1) return;
if(dp[x][y]==dp[x-1][y])
{
path[x]=0;
print(x-1,y);
}
else if(dp[x][y]==dp[x-1][y-a[x]]+a[x])
{
path[x]=1;
print(x-1,y-a[x]);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(dp,0,sizeof(dp));
memset(vis,0,sizeof(vis));
memset(path,0,sizeof(path));
for(int i=1;i<=m;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=m;i++)
{
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]);
if(dp[i-1][j]<dp[i-1][j-a[i]]+a[i])
{
dp[i][j]=dp[i-1][j-a[i]]+a[i];
}
else
{
dp[i][j]=dp[i-1][j];
}
}
// dp[i][j]=max(dp[i-1][j],dp[i-1][j-a[i]]+val[i]);
else
{
dp[i][j]=dp[i-1][j];
}
}
//
}
flag=0;
int k=dp[m][n];
print(m,n);
for(int i=1;i<=m;i++)
{
if(path[i]) printf("%d ",a[i]);
}
printf("sum:");
printf("%d\n",dp[m][n]);
}
return 0;
}