【算法| 差分 No.1】AcWing 797. 差分 & AcWing 798. 差分矩阵

个人主页:兜里有颗棉花糖

欢迎 点赞👍 收藏✨ 留言✉ 加关注💓本文由 兜里有颗棉花糖 原创

收录于专栏【手撕算法系列专栏

🍔本专栏旨在提高自己算法能力的同时,记录一下自己的学习过程,希望对大家有所帮助

🍓希望我们一起努力、成长,共同进步。

目录

  • [一、AcWing 797. 差分](#一、AcWing 797. 差分)
  • [二、AcWing 798. 差分矩阵](#二、AcWing 798. 差分矩阵)

一、AcWing 797. 差分

原题链接:点击直接跳转到该题目

关键代码:

  • b[l] += c;
  • b[r + 1] -= c;

解题代码

cpp 复制代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 1e5 + 10;
int nums[N];
int b[N];

void insert(int l,int r,int c)
{
    b[l] += c;
    b[r + 1] -= c;
}
int main()
{
    int n,m;
    cin >> n >> m;
    for(int i = 1;i <= n;i++) cin >> nums[i];
    while(m--)
    {
        int l,r,c;
        cin >> l >> r >> c;
        insert(l,r,c);
    }
    for(int i = 2;i <= n;i++) b[i] = b[i] + b[i - 1];
    for(int i = 1;i <= n;i++) nums[i] = nums[i] + b[i];
    for(int i = 1;i <= n;i++) printf("%d ",nums[i]);
    return 0;
}

二、AcWing 798. 差分矩阵

原题链接:点击直接跳转到该题目

代码关键:

  • b[x1][y1] += c;
  • b[x2 + 1][y1] -= c;
  • b[x1][y2 + 1] -= c;
  • b[x2 + 1][y2 + 1] += c;

解题代码

cpp 复制代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 1010;
int nums[N][N];
int b[N][N];

void insert(int x1,int y1,int x2,int y2,int c)
{
    b[x1][y1] += c;
    b[x1][y2 + 1] -= c;
    b[x2 + 1][y1] -= c;
    b[x2 + 1][y2 + 1] += c;
}

int main()
{
    int n,m,q;
    cin >> n >> m >> q;
    for(int i = 1;i <= n;i++)
        for(int j = 1;j <= m;j++)
            cin >> nums[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++)
        {
            b[i][j] = b[i - 1][j] + b[i][j - 1] + b[i][j] - b[i - 1][j - 1];
            nums[i][j] += b[i][j];
        }
    
    // 打印最终数组
    for(int i = 1;i <= n;i++)
    {
        for(int j = 1;j <= m;j++)
        {
            printf("%d ",nums[i][j]);
        }
        printf("\n");
    }
    return 0;
}
相关推荐
海底火旺几秒前
破解二维矩阵搜索难题:从暴力到最优的算法之旅
javascript·算法·面试
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3641 小时前
每日算法-250425
算法
烁3471 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法
我想进大厂2 小时前
图论---染色法(判断是否为二分图)
数据结构·c++·算法·深度优先·图论
油泼辣子多加2 小时前
【风控】稳定性指标PSI
人工智能·算法·金融
雾月553 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展