差分数组的作用

在某一个区间上快速加上某个数

#include<bits/stdc++.h>
using namespace std;
const int N =1e5 + 9;
int n, m;
int a[N], b[N];

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i ++) 
    {
        scanf("%d", &a[i]);
        b[i] = a[i] - a[i - 1];
    }
    
    int l, r, c;
    while (m -- )
    {
        scanf("%d%d%d", &l, &r, &c);
        b[l] += c;
        b[r + 1] -= c;
    }
    for(int i = 1; i <= n; i ++)
    {
        a[i] = a[i - 1] + b[i];
        cout << a[i] <<' ';
    }
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;
int n,m;
int s[N];

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n;i ++) scanf("%d", &s[i]);
    for(int i = n; i ; i --) s[i] -= s[i -1];
    
    while (m -- )
    {
        int l, r, c;
        cin >> l >> r >> c;
        s[l] += c; s[r + 1] -= c;
    }
    
    for(int i = 1; i <= n; i++)
    {
        s[i] += s[i - 1];
        cout << s[i] << " " ;
    }
    return 0;
}

二维差分

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, q;
int s[N][N];

int main()
{
    cin >> n >> m >> q;
    for(int i = 1; i <= n; i ++) // 初始化
        for(int j = 1; j <= m; j ++)
        {
            int x; cin >> x;
            s[i][j] += x;
            s[i + 1][j] -= x;
            s[i][j + 1] -= x;
            s[i + 1][j + 1] += x;
        }
    
    while(q -- ) //进行修改
    {
        int x1, y1, x2, y2, c;
        scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &c);
        s[x1][y1] += c;
        s[x2 + 1][y1] -= c;
        s[x1][y2 + 1] -= c;
        s[x2 + 1][y2 + 1] += c;
    }
    
    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]; 
        
    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= m; j ++)printf("%d ", s[i][j]); 
        puts("");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值