[HAOI2012] 音量调节
题目描述
一个吉他手准备参加一场演出。他不喜欢在演出时始终使用同一个音量,所以他决定每一首歌之前他都需要改变一次音量。在演出开始之前,他已经做好一个列表,里面写着每首歌开始之前他想要改变的音量是多少。每一次改变音量,他可以选择调高也可以调低。
音量用一个整数描述。输入文件中整数 $beginLevel$,代表吉他刚开始的音量,整数 $maxLevel$,代表吉他的最大音量。音量不能小于 $0$ 也不能大于 $maxLevel$。输入中还给定了 $n$ 个整数 $c_1,c_2,c_3,\cdots,c_n$,表示在第 $i$ 首歌开始之前吉他手想要改变的音量是多少。
吉他手想以最大的音量演奏最后一首歌,你的任务是找到这个最大音量是多少。
输入格式
第一行依次为三个整数 $n$,$beginLevel$ 和 $maxLevel$。
第二行依次为 $n$ 个整数 $c_1,c_2,c_3,\cdots,c_n$。
输出格式
输出演奏最后一首歌的最大音量。如果吉他手无法避免音量低于 $0$ 或者高于 $maxLevel$,输出 -1
。
样例 #1
样例输入 #1
3 5 10
5 3 7
样例输出 #1
10
提示
$1\le n\le 50$,$1\le c_i\le maxLevel$,$1\le maxLevel\le 1000$,$0\le beginLevel\le maxLevel$。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
/**************** 以下为快读 ****************/
static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer in;
// 在没有其他输入时返回 null
static String next() {
try {
while (in == null || !in.hasMoreTokens())
in = new StringTokenizer(r.readLine());
return in.nextToken();
} catch (Exception e) {
}
return null;
}
static int nextInt() {
return Integer.parseInt(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static final int N = 1010;
static int n, begin, max;
static int[] c = new int[N];
static int[][] f = new int[N][N];//前i首歌,总音量为j,能否到达
public static void main(String[] args) throws Exception{
n = nextInt();//n首歌曲
begin = nextInt();//吉他刚开始的音量
max = nextInt();//吉他的最高音量
for(int i = 1;i <= n;i ++) {
c[i] = nextInt();
}
f[0][begin] = 1;//1代表可以到达 0代表不可以到达
for(int i = 1;i <= n;i ++) {
for(int j = 0;j <= max;j ++) {
if(f[i - 1][j] == 1 && j + c[i] <= max)
f[i][j + c[i]] = 1;
if(f[i - 1][j] == 1 && j - c[i] >= 0)
f[i][j - c[i]] = 1;
}
}
for(int i = max;i >= 0;i --) {
if(f[n][i] == 1) {
out.print(i);
out.flush();
return;
}
}
out.print("-1");
out.flush();
out.close();
}
}