CD UVA - 624--01背包

题目

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

题意

一共有 t 的时间,有n首歌,每首歌都有对应的时间,往这 t 的时间里面放歌,尽可能的使空白时间最少。输出最大时间以及选择的歌曲。

分析

这个题的难点就在于输出路径,我们用一个二维dp数组来记录路径,dp[ i ][ j ]表示前 i 首歌,在 j 时间内能利用的最大值。那么,dp[ i ][ j ]=max(dp[i-1][ j ],dp[i-1][ j-a[ i ] ]+a[ i ])。更新完dp数组后,从后往前找,如果dp[ i ][ j ]==dp[i-1][ j-a[ i ]]+a[ i ],那就说明第 i 首歌我们选了(其实我也不是很懂,也是看的别人的博客,就单纯为了记一下路径输出的方法)。

代码

#include<cstdio>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=1e5+5;
int a[22],ans[22],dp[22][N];//dp[i][j]表示前i首歌,在j时间内能利用的最大值  
int main()
{
    int t,n;
    while(~scanf("%d",&t))
    {
    	scanf("%d",&n);
    	for(int i=1;i<=n;i++)
    		scanf("%d",&a[i]);
    	memset(dp,0,sizeof(dp));
    	for(int i=1;i<=n;i++)
    	{
    		for(int j=1;j<=t;j++)
    		{
    			if(j<a[i])
    				dp[i][j]=dp[i-1][j];
    			else
    				dp[i][j]=max(dp[i-1][j],dp[i-1][j-a[i]]+a[i]);
			}
		}
		int cnt=0;
		for(int i=n,j=t;i>0;i--)
		{
			if(j-a[i]>=0&&dp[i][j]==dp[i-1][j-a[i]]+a[i])//说明第i首歌是被选出来的  
			{
				ans[cnt++]=a[i];
				j-=a[i];
			}
		}
		for(int i=cnt-1;i>=0;i--)//注意逆序输出  
			printf("%d ",ans[i]);
		printf("sum:%d\n",dp[n][t]);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值