DP问题,背包问题,f[i][j] 表示只考虑前i个物品,除以k余数为j的情况所能拿到的最大价值。
每一步考虑拿或者不拿第i件物品,不拿f[i - 1][j]
如果拿的话,首先去掉第i件物品,求余k,再加上i的价值。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int N = 110, n, k;
static int f[][] = new int[N][N], w[] = new int[N];
public static void main(String[] args) throws IOException {
for (int i = 0; i < N; i++) Arrays.fill(f[i], -0x3f);
f[0][0] = 0;
String s[] = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
k = Integer.parseInt(s[1]);
for (int i = 1; i <= n; i++) {
int w = Integer.parseInt(br.readLine());
for (int j = 0; j < k; j++) {
f[i][j] = max(f[i - 1][j], f[i - 1][mod(j - w, k)] + w);
}
}
System.out.println(f[n][0]);
}
static int mod(int x, int y) {
return ((x % y) + y) % y;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
}