简单dp

题目:
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.

大致题意:
你前面有一段很长的车程。你有录音机,但不幸的是你最好的音乐还在播放

CD。你需要把它录在磁带上,所以要解决的问题是:你的磁带有N分钟长。怎么

从CD中选择曲目以充分利用磁带空间,并尽可能缩短未使用的空间。

假设:

•CD上的曲目数量不超过20首

•音轨长度不超过N分钟

•音轨不重复

•每条轨道的长度表示为整数

•N也是整数

程序应该找到最能填满磁带的磁道集,并按与

曲目存储在CD上

题解:
一道简单dp题,因为对一首歌只有录与不录两种选择,我们就可以用递归模拟出全部情况,选出时间最长的一种情况,即可解题。

代码如下:

#include<iostream>
#include<algorithm>

using namespace std;

int n,t,CD[20],ans[20],sum,d;

void dp(int num,int time,int a[20],int w)
{
	if(time>n) return ;
	if(num==t+1) return ;
	if(sum<time)
	{
		for(int i=0;i<t;i++) ans[i]=a[i];
		sum=time;
		d=w;
	}
	dp(num+1,time,a,w);
	a[w]=CD[num];
	dp(num+1,time+CD[num],a,w+1);

}

int main()
{
	int a[20];
	while(cin>>n>>t)
	{
		for(int i=0;i<t;i++) cin>>CD[i];
		dp(0,0,a,0);
		for(int i=0;i<d;i++) cout<<ans[i]<<" ";
		cout<<"sum:"<<sum<<endl;
		sum=0;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值