# 2.6-Java普及组 蓝桥算法训练营

Feishi11 2023-02-06 20:12:50

# 采药：背包01 完全背包

``````import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int m = sc.nextInt();
int[] dp = new int[1005];
int[] w = new int[m + 1];
int[] v = new int[m + 1];
for (int i = 1; i <= m; i++) {
w[i] = sc.nextInt();
v[i] = sc.nextInt();
}
for (int i = 1; i <= m; i++) {
//这里改for (int j = w[i]; j <=t; j++)就是完全背包
for (int j = t; j >= w[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - w[i]] + v[i]);
}
}
System.out.println(dp[t]);
}
}
``````

# 状态转移 (i-1, j)即上面来,(i, j-1)即左边来两两取最大值加上当前的值就好了

``````
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] a = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
a[i][j] = sc.nextInt();
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
a[i][j] = Math.max(a[i][j - 1], a[i - 1][j]) + a[i][j];
}
}
System.out.println(a[n][m]);
}
}
}
``````

# dp[i][j]只需要用到这一层和上一层的元素可以压缩成一维

``````import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int[] a = new int[1005];
int max = -1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int x = sc.nextInt();
a[j] = Math.max(a[j - 1], a[j]) + x;
max = Math.max(a[j], max);
}
}
System.out.println(max);
}
}
}``````

# 摆花：

``````//i表示有多少种花，j表示有多少盆花，k表示某种花放多少盆

import java.util.Scanner;

public class 摆花 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int mod = (int) (1e6 + 7);
int[][] dp = new int[n + 1][m + 1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
int a = sc.nextInt();
for (int j = 0; j <= m; j++) {
//注意这里要j-k>=0
for (int k = 0; k <= a && j - k >= 0; k++) {
dp[i][j] = (dp[i][j] + dp[i - 1][j - k]) % mod;
}
}
}
System.out.println(dp[n][m]);
}
}
``````

...全文
18 回复 打赏 收藏 举报

4.1w+

2023-02-06 20:12

刷题！