差分數組(一維)

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    /**
     * arr數組 [left, right] 區間每一個元素加 num
     * @param helper
     * @param left
     * @param right
     * @param num
     */
    private static void add(int[] helper, int left, int right, int num) {
        helper[left] += num;
        helper[right + 1] -= num;
    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {

            int n = in.nextInt();

            int q = in.nextInt();

            int[] arr = new int[n + 1];
            int[] helper = new int[n + 2];

            for (int i = 1; i <= n; ++ i) {
                arr[i] = in.nextInt();
                add(helper, i, i, arr[i]);
            }

            while (q -- > 0) {

                int l = in.nextInt();
                int r = in.nextInt();
                int c = in.nextInt();

                add(helper, l, r, c);
            }

            /**
             * 查分數組:ai = b1 + b2 + ... + bi
             */

            int sum = 0;
            for (int i = 1; i <= n; ++ i) {
                sum += helper[i];
                arr[i] = sum;
            }

            System.out.print(arr[1]);
            for (int i = 2; i <= n; ++ i) {
                System.out.print(" " + arr[i]);
            }
            System.out.println();

        }
    }
}
相關文章
相關標籤/搜索