使用BufferedReader与BufferedWriter是习惯,在输入输出数据不那么大的时候可以使用Scanner与sout替换
视频中的一维版代码
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] temp = reader.readLine().split(" ");
int n1 = Integer.parseInt(temp[0]), n2 = Integer.parseInt(temp[1]), m = Integer.parseInt(temp[2]);
int mod = (int) 1e9+7; int[] f = new int[100010];
f[0] = 1;
temp = reader.readLine().split(" ");
for (int i = 1; i <= n1; i++) {
int p = Integer.parseInt(temp[i-1]);
for (int j = p; j <= m; j++) {
f[j] = ( f[j] + f[j-p] ) % mod;
}
}
temp = reader.readLine().split(" ");
for (int i = 1; i <= n2; i++) {
int p = Integer.parseInt(temp[i-1]);
for (int j = m; j >= p; j--) {
f[j] = ( f[j] + f[j-p] ) % mod;
}
}
System.out.println(f[m]);
}
}
二维版代码
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] p = reader.readLine().split(" ");
int n1 = Integer.parseInt(p[0]), n2 = Integer.parseInt(p[1]), m = Integer.parseInt(p[2]);
int mod = (int) 1e9+7;
//f[i][j] 表示的对于前i种硬币,需要凑出的数值为j时的选法数量。
int[][] f = new int[n1+n2+1][m+1];
for (int i = 1; i <= n1+n2; i++) {
//对于前i种硬币,总面值为0时只有一种选法
f[i][0] = 1;
}
p = reader.readLine().split(" ");
for (int i = 1; i <= n1; i++) {
int P = Integer.parseInt(p[i-1]);
//因为j=0时无论有几种硬币可以选,答案都是1,所以这里跳过,下同。
for (int j = 1; j <= m; j++) {
if (j >= P){
f[i][j] = (f[i-1][j] + f[i][j-P]) % mod;
}else{
f[i][j] = f[i-1][j];
}
}
}
p = reader.readLine().split(" ");
for (int i = n1 + 1; i <= n1+n2; i++) {
int P = Integer.parseInt(p[i-n1-1]);
for (int j = 1; j <= m; j++) {
if (j >= P){
f[i][j] = (f[i-1][j] + f[i-1][j-P]) % mod;
}else{
f[i][j] = f[i-1][j];
}
}
}
System.out.println(f[n1+n2][m]);
}