不太会改进
思路:
把输入的两个二维数组换为两个一维数组,非零数字对应,无则补0;
最后这两个一维数组的对应下标相乘
package _2_17_稀疏向量_60;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int weiShu = scanner.nextInt();
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
int[] a = new int[weiShu];
int[] b = new int[weiShu];
//分别给两个数组赋值
for (int i = 0; i < weiShu; i++) {
a[i] = 0;
b[i] = 0;
}
int[][] martix1 = new int[n1][2];
int[][] martix2 = new int[n2][2];
for (int i = 0; i < martix1.length; i++) {
for (int j = 0; j < martix1[0].length; j++) {
martix1[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < martix2.length; i++) {
for (int j = 0; j < martix2[0].length; j++) {
martix2[i][j] = scanner.nextInt();
}
}
for(int i = 0; i < martix1.length; i++){
a[martix1[i][0]-1] = martix1[i][1];
}
for (int i = 0; i < martix2.length; i++) {
b[martix2[i][0]-1] = martix2[i][1];
}
long sum = 0;
for (int i = 0; i < weiShu; i++) {
sum += (a[i]*b[i]);
}
System.out.println(sum);
}
}