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

时间:2022-07-28
本文章向大家介绍UVA624 (01背包问题+打印路径),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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代码如下

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]);
		}
	}	
}