题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String a, b, c;
try {
a = r.readLine();
b = r.readLine();
c = r.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
int i = 0, j, k, n = 0, l, tol = 0, weight = 0, t, ans = 0;
char[] ch1 = a.toCharArray();
l = ch1.length;
do {
n *= 10;
n += ch1[i] - '0';
i++;
} while (i < l);
int[] wt = new int[n];
int[] ct = new int[n];
char[] ch2 = b.toCharArray();
char[] ch3 = c.toCharArray();
parsing(ch2, wt);//获得每一种砝码的重量
parsing(ch3, ct);//获得每一种砝码的数量
i = 0;
do {//遍历计算总重量
tol += wt[i] * ct[i];
i++;
} while (i < n);
int[] mark = new int[tol + 1];
mark[0] = 1;//称重重量0包含,置为1
i = 0;
do {//遍历种类
l = ct[i];
j = 0;
do {//遍历每种的数量
weight += wt[i];//当前砝码加入称重时的最大重量
mark[weight] = 1;//当前砝码都加入时的总重量,置为1
k = weight - 1;
do {//逆序遍历,有1,加上当前砝码重量,可称重量置为1
if (mark[k] == 1) {
t = k + wt[i];
mark[t] = 1;
}
k--;
} while (k > -1);
j++;
} while (j < l);
i++;
} while (i < n);
i = 0;
do {//数组元素为1,表示该下标重量可称
if (mark[i] == 1) ans++;
i++;
} while (i < tol + 1);
System.out.print(ans);
}
//获得重量和数量
public static void parsing(char[] chs, int[] arr) {
int j = 0, k = 0, num = 0;
int l = chs.length;
do {
if (chs[j] == ' ') {
arr[k++] = num;
num = 0;
j++;
continue;
}
num *= 10;
num += chs[j] - '0';
if (j == l - 1) arr[k] = num;
j++;
} while (j < l);
}
}
网易游戏公司福利 594人发布