UVA-624

题目
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
题目大意
你有一个n分钟长的空磁带,有t首喜欢的音乐,第i首音乐有长度a[i]。你需要把音乐录进磁带,使得磁带剩余的时间越短越好,求你录进磁带的音乐时长,并按输入顺序将选择的音乐时长输出。
解题思路
很明显是01背包问题。t首音乐时长相当于物品,n分钟长的空磁带相当于背包容量。
然而这道题的难点是,输出选则哪些音乐时长的。
f[i][j]表示在前i首歌选择若干首歌使得时长为j,并把能达到的最大时长记录在f[i][j]中

j-a[i]>=0 时 f[i][j]=max(f[i][j],f[i-1][j-a[i]]+a[i]])
j-a[i]<0 时 f[i][j]= f[i-1][j]
这样我们就可以,找到最大时长并根据最大时长逆推回去,把选择的音乐时长输出。(通过让第i个阶段与第i-1个阶段比较的方法)

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int a[10101],u[101],f[30][101010];
int tot,nbr;
int main()
{
	int v,n;
	while (~scanf("%d",&v))
	{
		scanf("%d",&n);
		for (int i=1;i<=n;i++)
		  scanf("%d",&a[i]);
		memset(f,0,sizeof(f));  
		for (int i=1;i<=n;i++)
		  for (int j=0;j<=v;j++)
		    {
		    f[i][j]=f[i-1][j];
		    if (j-a[i]>=0) f[i][j]=max(f[i][j],f[i-1][j-a[i]]+a[i]);
		    }
		int val;
		nbr=0;    
		for (int i=1;i<=v;i++)
		  if (f[n][i]!=0) val=f[n][i]; 
		tot=val;   
		for (int i=n;i>=1;i--) 
		{
			if (f[i][val]==f[i-1][val-a[i]]+a[i])
			{
				val-=a[i];
				u[++nbr]=a[i];
			}
		}   
		for (int i=nbr;i>=1;i--)
		  printf("%d ",u[i]);
		printf("sum:%d\n",tot);    
	}
}
发布了12 篇原创文章 · 获赞 0 · 访问量 127

猜你喜欢

转载自blog.csdn.net/weixin_45723759/article/details/103978113