有些重点需要注意的点,矩阵乘积之后要开 long 类型接收数据, 单纯按照题意计算会超时,分析时间复杂度可以知道,
复杂度为前面矩阵的行列的乘积与后面矩阵的列数的积;所以从左往右为 dn2 从右往左为 nd2
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[][] Q = new int[n][d];
int[][] Kt = new int[d][n];
int[][] V = new int[n][d];
int[] W = new int[n];
for (int i = 0; i < n; i ++) {
for (int j = 0; j < d; j ++) {
Q[i][j] = in.nextInt();
}
}
for (int j = 0; j < n; j ++) {
for (int i = 0; i < d; i ++) {
Kt[i][j] = in.nextInt();
}
}
for (int i = 0; i < n; i ++) {
for (int j = 0; j < d; j ++) {
V[i][j] = in.nextInt();
}
}
for (int i = 0; i < n; i ++) {
W[i] = in.nextInt();
}
// 输入结束
long[][] nums1 = qualify1(Kt, V);
for (int i = 0; i < Q.length; i ++) { // 先将权重向量乘入 还是 存粹的 从右往左算,都不影响答案;
for (int j = 0; j < Q[0].length; j ++) {
Q[i][j] = W[i] * Q[i][j];
}
}
long[][] nums2 = qualify2(Q, nums1);
for (int i = 0; i < nums2.length; i ++) {
for (int j = 0; j < nums2[0].length; j ++) {
System.out.print(nums2[i][j] + " ");
}
System.out.println();
}
}
public static long[][] qualify1(int[][] Q, int[][] Kt) { // 入参为两个整型数组的; 后者是懒得写了,直接复制粘贴
int row = Q.length;
int col = Kt[0].length;
long[][] ans = new long[row][col];
for (int i = 0; i < row; i ++) {
for (int j = 0; j < col; j ++) {
long res = 0L;
for (int k = 0; k < Q[0].length; k ++) {
res += Q[i][k] * Kt[k][j];
}
ans[i][j] = res;
}
}
return ans;
}
public static long[][] qualify2(int[][] Q, long[][] Kt) { // 入参前者为整型数组的,后者为long
int row = Q.length;
int col = Kt[0].length;
long[][] ans = new long[row][col];
for (int i = 0; i < row; i ++) {
for (int j = 0; j < col; j ++) {
long res = 0L;
for (int k = 0; k < Q[0].length; k ++) {
res += Q[i][k] * Kt[k][j];
}
ans[i][j] = res;
}
}
return ans;
}
}
// 这题目重点需要注意,矩阵内部的乘积和 很容易 爆 int ,所以需要开 long 类型