从这节开始又回答了令人头疼的动态规划,不过基本都是基础问题,不会像暑期打卡的某些题目一样难的没谱。
背包问题的证明网上太多太多了,这里就不给出了,上传图片是在太麻烦。
import java.io.*;
class Main{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int n, m;
static int N = 1010;
static int w[] = new int[N], v[] = new int[N], f[] = new int[N];
public static void main(String[] args) throws IOException {
String[] s = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
for (int i = 1 ; i <= n ; i++) {
s = br.readLine().split(" ");
w[i] = Integer.parseInt(s[0]);
v[i] = Integer.parseInt(s[1]);
}
for (int i = 1; i <= n; i++)
for (int j = m; j >= 0; j--)
if (j >= w[i])
f[j] = Math.max(f[j], f[j - w[i]] + v[i]);
pw.println(f[m]);
pw.flush();
pw.close();
br.close();
}
}