[CODEVS 3147] matrix multiplication 2, codevs3147
Description
Two n * n matrices are given, and m-times are asked about the value and of the given sub-matrix in their products.
Http://codevs.cn/problem/3147/
Analysis
The matrix multiplication of N3. prefix and optimization are required.
Row [s1]… Row [t1]
Col [s2]… Col [t2]
(S1, s2)-(t1, t2)
Row [x] * col [y] indicates that all elements of row x are used to multiply all elements of row y.
==>
= Row [s1] * col [s2] + row [s1] * col [s2 + 1] +... + Row [s1] * col [t2] + row [s1 + 1] * col [s2] +... + Row [s1 + 1] * col [t2] +... + Row [t1] * col [t2]
// The allocation law is not as obvious as it looks.
= Row [s1] * (col [s2] + col [s2 + 1] +... + Col [t2]) + row [s1 + 1] * (col [s2] + col [s2 + 1] +... + Col [t2]) +... + Row [t1] * (col [s2] + col [s2 + 1] +... + Col [t2])
= (Row [s1] + row [s1 + 1] +... + Row [t1]) * (col [s2] + col [s2 + 1] +... + Col [t2])
==> Use prefix and Processing
Note: row is actually equivalent to a matrix of 1 row and n columns, while col is equivalent to a matrix of n rows and 1 column. In the above formula, row [s1] +... + Row [t1] indicates to add the t1-s1 + 1 such matrix each element corresponds to the sum (with prefix and optimization) to obtain a new n rows and 1 columns matrix; col [s2] +... + Col [t2] uses the same method to obtain a new matrix with 1 row and n columns. After two new matrices are multiplied, a matrix with only one element is obtained. This element is the final answer.
Code
11809 ms 49 MB
# Include <cstdio> # include <algorithm> using namespace std; const int maxn = 2000 + 10; typedef int Matrix [maxn] [maxn]; typedef long LL; Matrix, b; int main () {int n, m; scanf ("% d", & n, & m); for (int x = 1; x <= n; x ++) for (int y = 1; y <= n; y ++) {scanf ("% d", & A [x] [y]); A [x] [y] + = A [x-1] [y];} // elements of the first x rows and for (int x = 1; x <= n; x ++) for (int y = 1; y <= n; y ++) {scanf ("% d", & B [x] [y]); B [x] [y] + = B [x] [Y-1];} // elements of the first y column and for (int I = 0; I <m; I ++) {int x1, y1, x2, y2; scanf ("% d", & x1, & y1, & x2, & y2 ); if (x1> x2) swap (x1, x2); if (y1> y2) swap (y1, y2); LL ans = 0; for (int I = 1; I <= n; I ++) ans + = (LL) (A [x2] [I]-A [x1-1] [I]) * (B [I] [y2]-B [I] [y1-1]); printf ("% lld \ n", ans);} return 0 ;}
Home Page
Http://blog.csdn.net/qq_21110267