AcWing 1013. 机器分配
原题链接
简单
作者:
不知名的fE
,
2024-12-06 22:48:57
,
所有人可见
,
阅读 1
dfs方法
import java.util.*;
import java.io.*;
public class Main {
static final int N = 20;
static int[][] f = new int[N][N], v = new int[N][N], w = new int[N][N];
static ArrayList<int[]> ans = new ArrayList<>();
static PrintWriter out = new PrintWriter(System.out);
static int n, m;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] str = sc.nextLine().split(" ");
n = Integer.parseInt(str[0]);
m = Integer.parseInt(str[1]);
for (int i = 1; i <= n; i++) {
str = sc.nextLine().split(" ");
for (int j = 1; j <= m; j++) {
v[i][j] = j;
w[i][j] = Integer.parseInt(str[j - 1]);
}
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
for (int k = 1; k <= v[i][k] && v[i][k] <= j; k++)
f[i][j] = Math.max(f[i][j], f[i - 1][j - v[i][k]] + w[i][k]);
}
out.println(f[n][m]);
for (int i = 1; i <= n; i++) ans.add(new int[]{i, 0});//可能出现没有分配的情况
dfs(n, m);
ans.sort((o1, o2) -> o1[0] - o2[0]);//排序或者倒着输出
for (int[] item : ans) out.println(item[0] + " " + item[1]);
out.flush();
}
static void dfs(int i, int j) {
if (i <= 0 || j < 0) return;
if (f[i][j] == f[i - 1][j]) dfs(i - 1, j);
else {
for (int k = 1; k <= v[i][k] && v[i][k] <= j; k++) {
if (f[i][j] == f[i - 1][j - v[i][k]] + w[i][k]) {
ans.set(i - 1, new int[]{i, k});
dfs(i - 1, j - v[i][k]);//这里注意一下索引的偏移即可
return;
}
}
}
}
}