UVA624

来源:互联网 发布:mac如何缩小照片kb 编辑:程序博客网 时间:2024/06/05 05:03

UVA 624 01背包路径记录

将价值和体积等同的01背包路径记录,开一个visit[i][j]来记录路径,因为题目要按输入的顺序输出,比如 9 8 4 2 输出 8 2而不是2 8,所以在一开始的循环中i是逆序从n到1,自己动手写一下路径的表或者用断点看看就应该会明白了

Description

  • 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

代码

c++#include<iostream>#include<stdio.h>#include<cstring>#include<cmath>using namespace std;const int maxn = 100001;int dp[maxn];int visit[25][10005];int main(){    int n,nt;    while (scanf("%d%d",&n,&nt)!=EOF)    {        memset(dp,0,sizeof(dp));        int track[25];        memset(visit,0,sizeof(visit));        for (int i = 0;i<nt;i++)        {           scanf("%d",&track[i]);        }        for (int i = nt-1;i>=0;i--)          for (int j = n;j>=track[i];j--)          {            if (dp[j-track[i]]+track[i] > dp[j])            {                visit[i][j] = 1;                dp[j] = dp[j-track[i]]+track[i];            }          }        int j = n;        for (int i = 0;i<nt;i++)        {           if (visit[i][j])            {                 printf("%d ",track[i]);                 j -= track[i];            }        }        printf("sum:%d\n",dp[n]);    }    return 0;}
0 0
原创粉丝点击