1 条题解

  • 0
    @ 2006-5-24 14:52:58

    【例62.2】 相邻数之和

    解题思路

    枚举行偏移与列偏移各-1~1,排除(0,0)本点,保留未越界的位置并求和,最多8个邻居。

    正确性说明

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

    易错点

    指定c是行、r是列,均为0起始;不能把中心也加进去。

    复杂度

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

    参考代码(C++11)

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

    信息

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