Uva--624(动规,路径)

2014-07-30 12:27:46

 CD 

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背包问题,但是加了个路径记录。如果把01背包写成一维数组(滚动数组)形式的话可能不怎么好理解。但是回归到最初的动态转移方程dp[i][j] = max(dp[i-1][j],dp[i-1][j-v[i]]+v[i]).就能理解,开个path[i][j]的二维数组来记录背包容量为 j 时 v[i] ,放与不放的情况(1就是放,0是不放)。要注意的是输出路径时如果 j 的初始值是max(背包总大小)的话要先考虑最后一个放进背包的v[i],这个顺序要琢磨一下。
 1 /*************************************************************************
 2     > File Name: n.cpp
 3     > Author: Nature
 4     > Mail: 564374850@qq.com 
 5     > Created Time: Tue 29 Jul 2014 11:14:32 PM CST
 6 ************************************************************************/
 7 
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cstdlib>
11 #include <cmath>
12 #include <iostream>
13 #include <algorithm>
14 using namespace std;
15 
16 int N,n,v[25],dp[10005],path[25][10005];
17 
18 int main(){
19     while(scanf("%d%d",&N,&n) == 2){
20         memset(dp,0,sizeof(dp));
21         memset(path,0,sizeof(path));
22         for(int i = 0; i < n; ++i)
23             scanf("%d",&v[i]);
24         for(int i = 0; i < n; ++i){
25             for(int j = N; j >= v[i]; --j){
26                 if(dp[j - v[i]] + v[i] > dp[j]){
27                     dp[j] = dp[j - v[i]] + v[i];
28                     path[i][j] = 1; //容量为j的背包里面装v[i]
29                 }
30             }
31         }
32         for(int i = n - 1,j = N; i >= 0; --i){
33             if(path[i][j]){
34                 printf("%d ",v[i]);
35                 j -= v[i];
36             }
37         }
38         printf("sum:%d\n",dp[N]);
39     }
40     return 0;
41 }

 


posted @ 2014-07-30 12:33  Naturain  阅读(101)  评论(0编辑  收藏  举报