【01背包】【HAOI2012】音量调节

题目描述

        一个吉他手准备参加一场演出。他不喜欢在演出时始终使用同一个音量,所以他决定每一首歌之前他都需要改变一次音量。在演出开始之前,他已经做好一个列表,里面写着每首歌开始之前他想要改变的音量是多少。每一次改变音量,他可以选择调高也可以调低。

        音量用一个整数描述。输入文件中整数beginLevel,代表吉他刚开始的音量,整数maxLevel,代表吉他的最大音量。音量不能小于0也不能大于maxLevel。输入中还给定了n个整数c1,c2,c3,...,cn,表示在第i首歌开始之前吉他手想要改变的音量是多少。    

        吉他手想以最大的音量演奏最后一首歌,你的任务是找到这个最大音量。

      输入输出格式

        【输入格式】:

        第一行依次为三个整数n, beginLevel, maxLevel。

        第二行依次为n个整数 c1,c2,c3,...,cn。

        数据规模:

        1<=n<=50, 1<=ci<=maxLevel, 1<=maxLevel<=1000, 0<=beginLevel<=maxLevel

        【输出格式】:

        输出演奏最后一首歌的最大音量。如果吉他手无法避免音量低于0或者高于maxLevel,输出-1。

      【输入样例】:                                                    【输出样例】

        3 5 10                                                                       10

        5 3 7

        F【i,j】表示第i首歌曲时,音量j可否到达。

        初始化F【0】【befinLevel】=1;

        做背包DP即可。

#include<iostream>
#include<iomanip>
#include<cstring>
#include<queue>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<stdio.h>
using namespace std;
int n,s,maxx;
bool f[55][1005];
int main()
{
	scanf("%d%d%d",&n,&s,&maxx);
	f[0][s]=1;
	for(int i=1;i<=n;i++)
	{
		int x;
		scanf("%d",&x);
		for(int j=0;j<=maxx;j++)
		{
			if(j-x>=0&&f[i-1][j-x])
			{
				f[i][j]=1;
			}
			if(j+x<=maxx&&f[i-1][j+x])
			{
				f[i][j]=1;
			}
		}
	}
	for(int i=maxx;i>=0;i--)
	{
		if(f[n][i])
		{
			printf("%d",i);
			return 0;
		}
	}
	printf("-1");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/dy_dream/article/details/80354941
今日推荐