#P16668. [CSPro 30] 矩阵运算

    ID: 18753 远端评测题 1000ms 512MiB 尝试: 0 已通过: 0 显示难度普及− 上传者: 标签>模拟2023矩阵运算矩阵乘法CSPro

[CSPro 30] 矩阵运算

Background

The testdata on Luogu is for non-official communication only and is not official testdata. Official judging link: https://www.cspro.org/。

Problem Description

$\text{Softmax}(\frac{Q \times K^T}{\sqrt{d}}) \times V$ is the core expression of the attention module in Transformers, where QQ, KK, and VV are all matrices with nn rows and dd columns, KTK^T denotes the transpose of matrix KK, and ×\times denotes matrix multiplication.

To make computation easier, student Dundun simplifies Softmax into an element-wise multiplication by a one-dimensional vector WW of length nn:

(W⋅(Q×KT))×V(W \cdot (Q \times K^T)) \times V

Element-wise multiplication here means multiplying corresponding positions. Let W(i)W^{(i)} be the ii-th element of vector WW. That is, every element in the ii-th row of (Q×KT)(Q \times K^T) is multiplied by W(i)W^{(i)}.

Given matrices QQ, KK, and VV, and vector WW, compute the result produced by Dundun using the simplified formula.

Input Format

Read input from standard input.

The first line contains two positive integers nn and dd separated by spaces, representing the size of the matrices.

Then matrices QQ, KK, and VV are given in order. Each matrix is given in nn lines, and each line contains dd integers separated by spaces. The jj-th number in the ii-th line corresponds to the element in row ii and column jj of the matrix.

The last line contains nn integers, representing vector WW.

Output Format

Write output to standard output.

Output nn lines in total, each containing dd integers separated by spaces, representing the computed result.

3 2
1 2
3 4
5 6
10 10
-20 -20
30 30
6 5
4 3
2 1
4 0 -5
480 240
0 0
-2200 -1100

Hint

Subtasks

70%70\% of the testdata satisfies: n≤100n \le 100 and d≤10d \le 10; all elements in the input matrices and vectors are integers, and their absolute values do not exceed 3030.

All testdata satisfies: n≤104n \le 10^4 and d≤20d \le 20; all elements in the input matrices and vectors are integers, and their absolute values do not exceed 10001000.

Hint

Please carefully estimate the value range after matrix multiplication, and use an appropriate data type to store the integers in the matrices.

Translated by ChatGPT 5