AcWing 4. 多重背包问题 I-java-朴素+空间优化
原题链接
简单
作者:
Astarion
,
2021-02-19 15:57:03
,
所有人可见
,
阅读 359
朴素
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
int N = Integer.parseInt(strs[0]);
int V = Integer.parseInt(strs[1]);
int[] v = new int[N+1];
int[] w = new int[N+1];
int[] s = new int[N+1];
int[][] f = new int[N+1][V+1];
for (int i = 1; i <= N; i++) {
strs = in.readLine().split(" ");
v[i] = Integer.parseInt(strs[0]);
w[i] = Integer.parseInt(strs[1]);
s[i] = Integer.parseInt(strs[2]);
}
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
for (int i = 1; i <= N; i++)
for (int j = 1; j <= V; j++)
for (int k = 0; k <= s[i] && k*v[i] <= j; k++)
f[i][j] = Math.max(f[i-1][j-k*v[i]]+k*w[i],f[i][j]);
out.write(f[N][V]+"");
out.flush();
out.close();
osw.close();
}
}
空间优化
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
int N = Integer.parseInt(strs[0]);
int V = Integer.parseInt(strs[1]);
int[] v = new int[N+1];
int[] w = new int[N+1];
int[] s = new int[N+1];
int[] f = new int[V+1];
for (int i = 1; i <= N; i++) {
strs = in.readLine().split(" ");
v[i] = Integer.parseInt(strs[0]);
w[i] = Integer.parseInt(strs[1]);
s[i] = Integer.parseInt(strs[2]);
}
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
for (int i = 1; i <= N; i++)
for (int j = V; j >= v[i]; j--)
for (int k = 0; k <= s[i] && k*v[i] <= j; k++)
//f[i][j] = Math.max(f[i-1][j-k*v[i]]+k*w[i],f[i][j]);
f[j] = Math.max(f[j-k*v[i]]+k*w[i],f[j]);
out.write(f[V]+"");
out.flush();
out.close();
osw.close();
}
}