[CODEVS 3147] 矩陣乘法 2,codevs3147

來源:互聯網
上載者:User

[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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.