BZOJ 2748: [HAOI2012]音量调节 (dp)

2748: [HAOI2012]音量调节

Time Limit: 3 Sec  Memory Limit: 128 MB Submit: 1814  Solved: 1148 [Submit][Status][Discuss]

Description

一个吉他手准备参加一场演出。他不喜欢在演出时始终使用同一个音量,所以他决定每一首歌之前他都要改变一次音量。在演出开始之前,他已经做好了一个列表,里面写着在每首歌开始之前他想要改变的音量是多少。每一次改变音量,他可以选择调高也可以调低。 音量用一个整数描述。输入文件中给定整数beginLevel,代表吉他刚开始的音量,以及整数maxLevel,代表吉他的最大音量。音量不能小于0也不能大于maxLevel。输入文件中还给定了n个整数c1,c2,c3…..cn,表示在第i首歌开始之前吉他手想要改变的音量是多少。 吉他手想以最大的音量演奏最后一首歌,你的任务是找到这个最大音量是多少。

Input

第一行依次为三个整数:n, beginLevel, maxlevel。 第二行依次为n个整数:c1,c2,c3…..cn。

Output

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

Sample Input

3 5 10 5 3 7

Sample Output

10

HINT

1<=N<=50,1<=Ci<=Maxlevel 1<=maxlevel<=1000

0<=beginlevel<=maxlevel

思路:

一看数据范围...长着一张dp的脸...

dp[i][j]表示经过i次调整后能否达到音量j.

初始化dp[0][beginlevel] = true.

按顺序转移就好了.

复杂度O(n*MAXlevel)

/* ***********************************************
Author :111qqz
Created Time :2017年04月02日 星期日 14时36分58秒
File Name :code/bzoj/2748.cpp
************************************************ */

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define PB push_back
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair

using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
bool dp[51][1005]; //dp[i][j]表示经过i次操作,能否达到音量j
int n,L,R;
int a[1005];
int main()
{
	#ifndef  ONLINE_JUDGE 
	freopen("code/in.txt","r",stdin);
  #endif
	ms(dp,0);
	cin>>n>>L>>R;
	for ( int i = 1 ; i <= n ; i++ ) cin>>a[i];
	dp[0][L] = true;
	for ( int i = 1 ; i <= n ; i++)
	{
	    for (int j = 0 ; j <= R ; j++)
	    {
		if (dp[i-1][j])
		{
		    if (j-a[i]>=0) dp[i][j-a[i]] = true;
		    if (j+a[i]<=R) dp[i][j+a[i]] = true;
		}
	    }
	}
	int ans = -1 ; //无解输出-1.
	for ( int i = 0 ; i <= R ; i++)if (dp[n][i]) ans = max(i,ans);
	cout<<ans<<endl;
  #ifndef ONLINE_JUDGE  
  fclose(stdin);
  #endif
    return 0;
}