前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >UVA624 (01背包问题+打印路径)

UVA624 (01背包问题+打印路径)

作者头像
dejavu1zz
发布2020-10-23 15:15:21
9130
发布2020-10-23 15:15:21
举报
文章被收录于专栏:奇妙的算法世界

UVA624

题目链接:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=565

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背包问题,难点就在这个打印路径,其实在找最大价值的时候,也间接的说明了选取的商品,可以使用一个布尔数组,如果满足 dp[j]<=dp[j-value[i]]+value[i],就让所对应的布尔数组为true,最后再逆序对布尔数组进行遍历。为什么要逆序遍历呢,这个问题想了很长时间才想明白。因为你是要打印最大价值时选中的商品,所以要不断的逆序打印,每循环一次,j的值要减去商品的值,表示剩下i件商品,剩下价值为j-value[i]时选中了哪些商品。

AC代码如下

代码语言:javascript
复制
import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner cin=new Scanner(System.in);
		while(cin.hasNext()) {
			int n=cin.nextInt();
			int m=cin.nextInt();
			boolean[][] b=new boolean[m][n+1];
			int[] value=new int[m];
			for(int i=0;i<m;i++) {
				value[i]=cin.nextInt();
			}
			int[] dp=new int[n+1];
			for(int i=0;i<m;i++) {
				for(int j=n;j>=value[i];j--) {
					if(dp[j]<=dp[j-value[i]]+value[i]) {
						dp[j]=dp[j-value[i]]+value[i];
						b[i][j]=true;
					}
				}
			}
			for(int i=m-1,j=n;i>=0;i--) {
				if(b[i][j]) {
					System.out.print(value[i]+" ");
					j-=value[i];
				}
			}
			System.out.println("sum:"+dp[n]);
		}
	}	
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/01/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • UVA624
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档