7.一维差分

一维差分

前缀和的逆运算

题目:
java 复制代码
 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 输入 n 和 m
        int n = sc.nextInt();
        int m = sc.nextInt();
        // 数组定义
        int[] a = new int[n + 1];  // a[1] 到 a[n] 为有效数据
        int[] b = new int[n + 1];  // b[1] 到 b[n] 为有效数据
        // 输入数组 a
        for (int i = 1; i <= n; i++) {
            a[i] = sc.nextInt();
        }
        // 初始化差分数组 b
        for (int i = 1; i <= n; i++) {
            insert(b, i, i, a[i]);
        }
        // 处理 m 次区间操作
        while (m-- > 0) {
            int l = sc.nextInt();
            int r = sc.nextInt();
            int c = sc.nextInt();
            insert(b, l, r, c);
        }
        // 计算并输出最终结果
        for (int i = 1; i <= n; i++) {
            b[i] += b[i - 1];
            System.out.print(b[i] + " ");
        }
        sc.close();
    }

    // 区间更新操作
    private static void insert(int[] b, int l, int r, int c) {
        b[l] += c;
        if (r + 1 <= b.length - 1) {
            b[r + 1] -= c;
        }
    }
相关推荐
手握风云-7 小时前
JavaEE 进阶第十二期:Spring Ioc & DI,从会用容器到成为容器(上)
java·spring·java-ee
梦幻精灵_cq7 小时前
《双征color》诗解——梦幻精灵_cq对终端渲染的数据结构设计模型式拓展
数据结构·python
7 小时前
java关于键盘录入
java·开发语言
马猴烧酒.7 小时前
JAVA后端对象存储( 图片分享平台)详解
java·开发语言·spring·腾讯云
梅梅绵绵冰8 小时前
springboot初步2
java·spring boot·后端
jiang_changsheng8 小时前
comfyui节点插件笔记总结新增加
人工智能·算法·计算机视觉·comfyui
TracyCoder1238 小时前
LeetCode Hot100(7/100)—— 3. 无重复字符的最长子串
算法·leetcode
重生之我是Java开发战士8 小时前
【优选算法】双指针法:移动0,复写0,快乐数,盛水最多的容器,有效三角形个数,二三四数之和
算法
独自破碎E8 小时前
【纵向扫描】最长公共前缀
java·开发语言
pp起床8 小时前
【苍穹外卖】Day03 菜品管理
java·数据库·mybatis