zoukankan      html  css  js  c++  java
  • 二维前缀和 & 二维差分

    二维前缀和

    求前缀和:(s_{i, : j} = s_{i - 1, : j} + s_{i, : j - 1} - s_{i - 1, : j - 1} + a_{i, : j})

    算部分和:(s_{x_2, : y_2} - s_{x_1 - 1, : y_2} - s_{x_2, : y_1 - 1} + s_{x_1 - 1, : y_1 - 1})

    #include <bits/stdc++.h>
    using namespace std;
    
    const char nl = '
    ';
    const int N = 1000 + 50;
    
    int a[N][N], s[N][N];
    
    int main(){
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int n, m, q;
        cin >> n >> m >> q;
    
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j)
                cin >> a[i][j];
    
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j)
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j];
    
        while (q--){
            int x1, y1, x2, y2;
            cin >> x1 >> y1 >> x2 >> y2;
            cout << s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1] << nl;
        }
    
        return 0;
    }
    
    

    二维差分

    (b_{x_1, : y_1} : += : c)

    (b_{x_2 + 1, : y_1} : -= : c)

    (b_{x_1, : y_2 + 1} : -= : c)

    (b_{x_2 + 1, : y_2 + 1} : += : c)

    #include <bits/stdc++.h>
    using namespace std;
    
    const char nl = '
    ';
    const int N = 100 + 50;
    
    int a[N][N], b[N][N];
    
    int main(){
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int n, m, q;
        cin >> n >> m >> q;
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j)
                cin >> a[i][j];
    
        // 构造
        for (int i = 1; i <= n; ++i){
            for (int j = 1; j <= m; ++j){
                b[i][j] += a[i][j];
                b[i + 1][j] -= a[i][j];
                b[i][j + 1] -= a[i][j];
                b[i + 1][j + 1] += a[i][j];
            }
        }
    
        // 区间操作
        while (q--){
            int x1, y1, x2, y2, c;
            cin >> x1 >> y1 >> x2 >> y2 >> c;
            b[x1][y1] += c;
            b[x2 + 1][y1] -= c;
            b[x1][y2 + 1] -= c;
            b[x2 + 1][y2 + 1] += c;
        }
    
        // 计算前缀和
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= m; ++j)
                b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
    
        // 输出
        for (int i = 1; i <= n; ++i){
            for (int j = 1; j <= m; ++j) cout << b[i][j] << ' ';
            cout << nl;
        }
    
        return 0;
    }
    
    
  • 相关阅读:
    python pyinotify模块详解
    lastpass密码管理工具使用教程
    MAMP 环境下安装Redis扩展
    SourceTree使用方法
    Mac securecrt 破解
    Memcache 安装
    Warning: setcookie() expects parameter 3 to be long, string given
    SQLSTATE[HY000] [2002] Connection refused
    插件管理无法访问
    光栅化渲染器
  • 原文地址:https://www.cnblogs.com/xiaoran991/p/14406679.html
Copyright © 2011-2022 走看看