本题将公式转换为代码即可,注意:
long long KT
与long long TMP
要放在main外防止溢出- 矩阵相乘时要想清楚定和动的分别是哪个矩阵的索引
#include <iostream>
const int N = 10000, D = 30;
using namespace std;
int Q[N][D];
int K[N][D];
int V[N][D];
int W[N];
long long KT[D][N];
long long TMP[N][N];
int main() {
int n, d;
cin >> n >> d;
//Q
for (int i = 0; i < n; i++) {
for (int j = 0; j < d; j++) {
cin >> Q[i][j];
}
}
//K
for (int i = 0; i < n; i++) {
for (int j = 0; j < d; j++) {
cin >> K[i][j];
}
}
//V
for (int i = 0; i < n; i++) {
for (int j = 0; j < d; j++) {
cin >> V[i][j];
}
}
//W
for (int i = 0; i < n; i++) {
cin >> W[i];
}
//K的转置
for (int i = 0; i < d; i++) {
for (int j = 0; j < n; j++) {
KT[i][j] = K[j][i];
}
}
//Q * KT
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
TMP[i][j] = 0;
for (int k = 0; k < d; k++) {
TMP[i][j] = TMP[i][j] + Q[i][k] * KT[k][j];
}
//W点乘
TMP[i][j] = (long long)W[i] * TMP[i][j];
}
}
//TMP * V
for (int i = 0; i < n; i++) {
for (int j = 0; j < d; j++) {
long long sum = 0;
for (int k = 0; k < n; k++) {
sum = sum + TMP[i][k] * V[k][j];
}
cout << sum <<" ";
}
cout << endl;
}
return 0;
}