UVA 624 ---CD 01背包路径输出

时间:2023-03-08 23:53:49
UVA 624 ---CD  01背包路径输出

DescriptionCD

UVA 624 ---CD  01背包路径输出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
4 10 12 9 8 2 sum:45

01背包输出路径;
#include<stdio.h>
#include<string.h> #define N 1100
#define max(a,b) (a>b?a:b) int v[N], dp[N][N], W, n; void Path(int n, int W)
{
if(n==) return ; if(dp[n-][W]==dp[n][W])
Path(n-, W);
else
{
Path(n-, W-v[n]);
printf("%d ", v[n]);
}
} int main()
{
while(scanf("%d%d", &W, &n)!=EOF)
{
int i, j;
memset(v, , sizeof(v));
memset(dp, , sizeof(dp));
for(i=; i<=n; i++)
scanf("%d", &v[i]); for(i=; i<=n; i++)
for(j=; j<=W; j++)
{
if(v[i]>j)
dp[i][j] = dp[i-][j];
else
dp[i][j] = max(dp[i-][j], dp[i-][j-v[i]]+v[i]);
} Path(n, W); printf("sum:%d\n", dp[n][W]);
}
return ;
}

一维数组:

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<stack>
#include<vector>
#include<map>
using namespace std;
#define N 2510
#define INF 0x3f3f3f3f
#define met(a, b) memset(a, b, sizeof(a))
typedef long long LL; int n, m, a[N], dp[N], path[N][N]; int main()
{
while(scanf("%d %d", &m, &n)!=EOF)
{
met(dp, );
met(path, );
for(int i=; i<n; i++)
scanf("%d", &a[i]);
for(int i=; i<n; i++)
{
for(int j=m; j>=a[i]; j--)
{
///dp[j] = max(dp[j], dp[j-a[i]]+a[i]);
if(dp[j] < dp[j-a[i]]+a[i])
{
path[i][j] = ;
dp[j] = dp[j-a[i]]+a[i];
}
}
}
int j = m, k = , ans[N] = {};
for(int i=n-; i>=; i--)
{
if(path[i][j])
{
ans[k++] = a[i];
j -= a[i];
}
}
for(int i=k-; i>=; i--)
printf("%d ", ans[i]);
printf("sum:%d\n", dp[m]);
}
return ;
}