UVa 624 - CD DP 0/1 背包问题
来源:互联网 发布:笔记软件哪个好 编辑:程序博客网 时间:2024/06/05 21:00
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 minutesOutput
Set of tracks (and durations) which are the correct solutions and string ``sum:" and sum of duration times.Sample Input
5 3 1 3 410 4 9 8 4 220 4 10 5 7 490 8 10 23 1 2 3 4 5 745 8 4 10 44 43 12 9 8 2
Sample Output
1 4 sum:58 2 sum:1010 5 4 sum:1910 23 1 2 3 4 5 7 sum:554 10 12 9 8 2 sum:45
Miguel A. Revilla
#include <cstdio>#include <cstring>const int MAX = 2000 + 5;int dp[MAX][MAX];int n, w;int c[MAX], ans[MAX];int maxValue(int a, int b){return a>b?a:b;}int main(){//freopen("in.txt","r",stdin);while(scanf("%d %d", &w, &n)==2){for(int i=1; i <= n; i++)scanf("%d", &c[i]);memset(dp,0,sizeof(dp));for(int i=1; i <= n; i++){for(int j=0; j <= w; j++)if(c[i] <= j)dp[i][j] = maxValue(dp[i-1][j], dp[i-1][j-c[i]]+c[i]);elsedp[i][j] = dp[i-1][j];}int length=0;for(int i=n, j=w; i > 0; i--){if(j-c[i]>=0 &&dp[i][j]==dp[i-1][j-c[i]]+c[i]){ans[length++] = c[i];j -= c[i];}}for(int i=length-1; i>=0; i--)printf("%d ", ans[i]);printf("sum:%d\n",dp[n][w]);}return 0;}
0/1 背包问题,加上结果之后的逆推,MAX 一开始是1000, WA了一次
1 0
- UVa 624 - CD DP 0/1 背包问题
- UVA 624 CD 0-1背包问题
- UVA 624 CD(DP + 01背包)
- UVA 624 CD(DP:01背包)
- UVA 624 CD 01背包(DP)
- UVa 624 CD (DP 01背包)
- uva 624 CD (0/1背包)
- UVa 624 CD (0-1背包)
- UVA 624 CD 0-1背包
- UVA - 624 CD 01背包问题
- UVA 624CD(01背包问题)
- UVA 624 CD(01背包+dp打印路径)
- uva 624 CD (0-1背包打印路径)
- UVA 624 CD (01 背包)
- UVA 624 CD (记录背包)
- 【UVA】624-CD(动态规划01背包问题)
- UVA NO.624 CD(打印路径,简单背包问题)
- UVA 624 CD (DP)
- 第四章、安装 CentOS 5.x 与多重开机小技巧
- 记录:LED灯驱动
- Android权限配置
- 第五章、首次登陆与在线求助 man page
- C++中的STL容器简介
- UVa 624 - CD DP 0/1 背包问题
- 毁灭感情的不是距离,而是怀疑
- c++ 容器类 概括性介绍
- 第六章、Linux 的文件权限与目录配置
- 安卓转屏实现4个方向+变换坐标原点位置
- Android4.x中ScrollView嵌套ListView,ListView不能完全显示总结、解决办法
- 第七章、Linux 文件与目录管理
- 在线英文写作辅助工具
- iOS7集成设置UINavigationBar字体大小,风格,颜色