题目
样例输入
8
6
5
0.342 0.211 0.155 0.149 0.143 0.286
1 2 4 2 1
1 2 3 3 1
0 1 2 3 4
0 1 3 4 2
0 1 1 6 2
0 1 1 5 3
3
5
0.143 0.571 0.083
0 0 1 6 3
1 1 4 3 1
0 1 3 4 2
3
5
0.667 0.250 0.158
0 3 3 3 1
1 1 4 4 0
1 6 1 1 1
3
5
0.158 0.316 0.368
1 1 4 3 1
1 1 5 3 0
0 3 4 2 1
3
5
0.083 0.417 0.500
0 3 3 2 2
1 3 4 2 0
1 1 2 3 3
3
5
0.167 0.250 0.583
0 0 1 4 5
0 0 2 4 4
1 4 2 2 1
2
5
0.385 0.615
0 5 2 2 1
1 4 3 1 1
2
5
0.222 0.778
1 1 4 2 2
1 2 6 1 0
样例输出
0.043 0.143 0.248 0.363 0.203
0.072 0.082 0.336 0.364 0.146
0.038 0.298 0.294 0.294 0.077
0.056 0.187 0.438 0.256 0.062
0.092 0.200 0.292 0.250 0.167
0.058 0.233 0.183 0.283 0.242
0.061 0.439 0.262 0.139 0.100
0.100 0.178 0.556 0.122 0.044
题解
这题的逻辑过于简单,只需要注意几个题干中完全不讲的问题,首先是题目中红框的那句话可以当成放屁,因为他自己下面的例子就不符合他自己的讲解,以及例子本身也不符合他说的矩阵乘法,这题应该分为两步,刚好可以写成两个函数
1.矩阵相乘
得到一个一行的矩阵和一个多行的矩阵,直接乘即可
//一个一行的矩阵和一个二维矩阵相乘
vector<double> MatrixM(vector<double> a, vector<vector<double>> r)
{
vector<double> res;
for (int i = 0; i < r.at(0).size(); i++)
{
double sum = 0;
for (int j = 0; j < a.size(); j++)
{
sum += a.at(j) * r.at(j).at(i);
}
res.push_back(sum);
}
return res;
}
2.归一化
乘出来会发现完全不是样例的样子,原来是因为样例归一化处理了
再写一个归一化的函数即可
//归一化
void NormalMatrix(vector<double>& mat)
{
double sum = 0;
for (auto i : mat)
{
sum += i;
}
auto i = mat.begin();
while (i != mat.end())
{
*i = *i / sum;
i++;
}
}
代码
#include <iostream>
#include <vector>
using namespace std;
//归一化
void NormalMatrix(vector<double>& mat)
{
double sum = 0;
for (auto i : mat)
{
sum += i;
}
auto i = mat.begin();
while (i != mat.end())
{
*i = *i / sum;
i++;
}
}
//一个一行的矩阵和一个二维矩阵相乘
vector<double> MatrixM(vector<double> a, vector<vector<double>> r)
{
vector<double> res;
for (int i = 0; i < r.at(0).size(); i++)
{
double sum = 0;
for (int j = 0; j < a.size(); j++)
{
sum += a.at(j) * r.at(j).at(i);
}
res.push_back(sum);
}
NormalMatrix(res);
return res;
}
int main()
{
vector<vector<double>> mat_res;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int m;
int b;
cin >> m >> b;
vector<double> mat_A;
for (int j = 0; j < m; j++)
{
double tem;
cin >> tem;
mat_A.push_back(tem);
}
vector<vector<double>> mat_R;
for (int j = 0; j < m; j++)
{
vector<double> tem1;
for (int k = 0; k < b; k++)
{
double tem2;
cin >> tem2;
tem1.push_back(tem2);
}
mat_R.push_back(tem1);
}
vector<double> tem_res = MatrixM(mat_A, mat_R);
mat_res.push_back(tem_res);
}
//输出
for (auto i : mat_res)
{
for (auto j : i)
{
printf_s("%.3f ", j);
}
printf_s("\n");
}
return 0;
}