二维前缀和与差分

二维前缀和:
 

原理:矩阵的前缀和存在一个地推关系,如下图所示

 

解决的问题: 子矩阵中所有数的和 

公式:a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1] + a[x1 - 1][y1 - 1];

 

code;
 

#include<iostream>
#include<cstdio>
#include<algorithm>

using namespace std;

const int N = 1100;
int a[N][N];
int n, m, q;

int main()
{
    scanf("%d%d%d", &n, &m, &q);
    for(int i = 1; i <= n ; i ++ )
        for(int j = 1 ; j <= m ;j ++ ){
            scanf("%d", &a[i][j]);
        }
    for(int i = 1 ;i <=n ;i ++ )
        for(int j = 1 ; j <= m ; j ++ ){
            a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i- 1 ][ j - 1];
        }
    while(q -- ){
        int x1, y1, x2, y2;
        
        scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
        int ans = a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1] + a[x1 - 1][y1 - 1];
        printf("%d\n", ans );
        
    }
    
    return 0;
}

 

二维差分:

 

原理:差分数组的前缀和就是原数组

 

 

解决的问题:子矩阵的每一个数都加上一个数,然后求原数组
  

code:

//不需要知道二维差分数组是怎么求的,初始化为0
#include<iostream>
#include<cstdio>

using namespace std;

const int N = 1100;

int a[N][N],d[N][N];
int n, m, q;
 
void insert(int x1, int y1, int x2, int y2, int c)
{
    d[x1][y1] += c;
    d[x2 + 1][y1] -= c;
    d[x1][y2 + 1] -= c;
    d[x2 + 1][y2 + 1] += c;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
     
    cin >> n >> m >> q;
    for(int i = 1 ; i <= n ; i ++ )
        for(int j = 1;j <= m ;j ++ ){
            cin >> a[i][j];
            
        }
    //对差分数组进行操作 初始化d数组都为0
    for(int i = 1; i <= n ;i ++ )
        for(int j = 1 ; j <= m; j ++ ){
            insert(i, j, i, j, a[i][j]);
        
        }
        
    while(q -- ){
        int x1, y1, x2, y2, c;
        cin >> x1 >> y1 >> x2 >> y2 >> c;
        insert(x1, y1, x2, y2, c);
    }
    
    //差分数组的前缀和就是原数组(记住就行)
    for(int i = 1; i <= n ;i ++)
        for(int j = 1 ; j <= m ;j ++){
             d[i][j] += d[i - 1][j] + d[i][j - 1] - d[i - 1][j - 1];
        }
        
    for(int i = 1;i <= n ;i ++){
        
    
        for(int j = 1; j <=m ;j ++){
            cout << d[i][j] << " ";
            
        }
        puts("");
        // cout << endl;        
    }
}

 


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值