1 条题解

  • 0
    @ 2004-11-22 15:54:17

    【例62.1】 矩阵加法

    解题思路

    先保存矩阵A,再逐格读B并加到相同下标,最后按原行列结构输出。

    正确性说明

    按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。

    易错点

    矩阵加法按同一位置,不是矩阵乘法。

    复杂度

    时间O(nm),空间O(nm)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n, m;
        cin >> n >> m;
        vector<vector<long long>> a(n, vector<long long>(m));
        for (auto &r : a)
            for (auto &x : r)
                cin >> x;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) {
                long long x;
                cin >> x;
                a[i][j] += x;
            }
        for (auto &r : a) {
            for (int j = 0; j < m; j++) {
                if (j)
                    cout << " ";
                cout << r[j];
            }
            cout << "\n";
        }
        return 0;
    }
    
    • 1

    信息

    ID
    404
    时间
    1000ms
    内存
    256MiB
    难度
    进阶
    标签
    递交数
    0
    已通过
    0
    上传者