[CODEVS 3147] 矩陣乘法 2,codevs3147
描述
給出兩個n*n的矩陣,m次詢問它們的積中給定子矩陣的數值和。
http://codevs.cn/problem/3147/
分析
直接 n3 的矩陣乘法肯定逾時, 要採用首碼和最佳化
row[s1] … row[t1]
col[s2] … col[t2]
(s1, s2) – (t1, t2)
row[x] * col[y] 表示用第 x 行的所有元素去乘第 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]
// 分配律, 其實並沒有看上去那麼顯然
= 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])
==> 用首碼和處理
注意: row 其實相當於一個 1 行 n 列的矩陣, 而 col 相當於一個 n 行 1 列的矩陣. 上式中 row[s1] + … + row[t1] 表示把 t1-s1+1 個這樣的矩陣每個元素對應的加起來 (用首碼和最佳化) 得到一個新的 n 行 1 列的矩陣; col[s2] + … + col[t2] 採用同樣方法得到一個新的 1 行 n 列的矩陣. 兩個新矩陣再相乘就得到一個只有一個元素的矩陣了, 該元素就是最終答案.
代碼
11809ms 49MB
#include<cstdio>#include<algorithm>using namespace std;const int maxn = 2000 + 10;typedef int Matrix[maxn][maxn];typedef long long LL;Matrix A, B;int main() { int n, m; scanf("%d %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]; } // 前 x 行元素和 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]; } // 前 y 列元素和 for(int i = 0; i < m; i++) { int x1, y1, x2, y2; scanf("%d %d %d %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;}
首頁
http://blog.csdn.net/qq_21110267