【UVA 624】【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 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个盘道,然后我们有一个磁带,我们需要将光盘内的音乐录制到磁带中。问我们应该怎么录制,才能使磁带中的空间剩余的最少。并且按照光盘内的顺序打印出来盘道的数值,和磁带的最大数值

解题思路:01背包的plus,求解磁带的最大容量,直接01背包就可以求解,记录输出录制成功盘道数值是升级的地方,我们可以做标记,在回溯回去,把路径打印出来

ac代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define maxn 100000
using namespace std;

int dp[maxn];
int num[maxn];
int pre[maxn];

void print(int i)
{
	if(pre[i])
	{
		print(pre[i]);
		printf("%d ",i-pre[i]);
	}
	else
	{
		printf("%d ",i);
		return ;//找到头,就返回 
	}
}
int main()
{
	int n,m;
	while(scanf("%d%d",&m,&n)!=EOF)
	{
		memset(dp,0,sizeof(dp));
		memset(num,0,sizeof(num));
		memset(pre,0,sizeof(pre));
		for(int i=1;i<=n;i++)
			scanf("%d",&num[i]);
		for(int i=1;i<=n;i++)
			for(int j=m;j>=num[i];j--)
				if(dp[j-num[i]]+num[i]>dp[j])
				{
					dp[j]=max(dp[j],dp[j-num[i]]+num[i]);
					pre[j]=j-num[i];//pre数组记录路径 
				}
		print(dp[m]);//递归寻找路径 
		printf("sum:%d\n",dp[m]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/81739538
cd