这是链接计算机软件能力认证考试系统
关键点:
1、矩阵相乘要注意看n和d的大小,题目给的n最大为,但d最大为20,所以可以先看看能不能凑出d×d的矩阵
2、还得掌握矩阵的运算:
这是70分的答案:
#include <iostream>
using namespace std;
//d远小于n,所以先用结合律算 K x V
int main()
{
int n, d;
cin >> n >> d;
int Q[n][d], K[n][d], V[n][d], W[n];
for(int cn = 0; cn < 3; cn++){
for(int i = 0; i < n; i++){
for(int j = 0; j < d; j++){
if(cn == 0){
cin >> Q[i][j];
} else if (cn == 1){
cin >> K[i][j];
} else {
cin >> V[i][j];
}
}
}
}
for(int i = 0; i < n; i++) cin >> W[i];
//(K x V) *W
long long res[d][d];
long long out[n][n];
long long temp;
//计算K的转置 x V得出d*d矩阵
for(int m = 0; m < d; m++){
for(int i = 0; i < d; i++){
temp = 0;
for(int j = 0; j < n; j++){
temp = temp + K[j][m] * V[j][i];
}
res[m][i] = temp;
}
}
for(int m = 0; m < n; m++){
for(int i = 0; i < d; i++){
temp = 0;
for(int j = 0; j < d; j++){
temp = temp + Q[m][j] * res[j][i];
}
temp = temp * (long long)W[m];
out[m][i] = temp;
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < d; j++){
cout << out[i][j] << " ";
}
cout << endl;
}
return 0;
}
这是100分的答案:
#include <iostream>
using namespace std;
//d远小于n,所以先用结合律算 K x V
int main()
{
int n, d;
cin >> n >> d;
int Q[n][d], K[n][d], V[n][d], W[n];
for(int cn = 0; cn < 3; cn++){
for(int i = 0; i < n; i++){
for(int j = 0; j < d; j++){
if(cn == 0){
cin >> Q[i][j];
} else if (cn == 1){
cin >> K[i][j];
} else {
cin >> V[i][j];
}
}
}
}
for(int i = 0; i < n; i++) cin >> W[i];
//(K x V) *W
long long res[d][d];
long long out[n][d];
long long temp;
for(int m = 0; m < d; m++){
for(int i = 0; i < d; i++){
temp = 0;
for(int j = 0; j < n; j++){
temp = temp + K[j][m] * V[j][i];
}
res[m][i] = temp;
}
}
for(int m = 0; m < n; m++){
for(int i = 0; i < d; i++){
temp = 0;
for(int j = 0; j < d; j++){
temp = temp + Q[m][j] * res[j][i];
}
temp = temp * (long long)W[m];
out[m][i] = temp;
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < d; j++){
cout << out[i][j] << " ";
}
cout << endl;
}
return 0;
}
区别就在输出out数组的大小里面,我真的不能理解这是为什么