Que12|797. 差分

67 阅读1分钟
题目:797. 差分 - AcWing题库
思路/想法:

image.png

image.png

代码实现:
// 差分
// InputMismatchException
import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] arr = new int[100010];
        int[] sub = new int[100010];
        for (int i = 1; i <= n; i++) {
            arr[i] = sc.nextInt();
            sub[i] = arr[i] - arr[i - 1];
        }
        while (m-- > 0) {
            int l = sc.nextInt();
            int r = sc.nextInt();
            int c = sc.nextInt();
            sub[l] += c;
            sub[r + 1] -= c;
        }
        for (int i = 1; i <= n; i++) {
            arr[i] = arr[i - 1] + sub[i];
            System.out.print(arr[i] + " ");
        }
    }
}


// 超时
// import java.util.*;
// public class Main{
//     public static void main(String[] args) {
//         Scanner sc = new Scanner(System.in);
//         int n = sc.nextInt();
//         int m = sc.nextInt();
//         int[] arr = new int[n + 1];
//         for (int i = 1; i <= n; i++) arr[i] = sc.nextInt();
//         while (m-- > 0) {
//             int l = sc.nextInt();
//             int r = sc.nextInt();
//             int count = sc.nextInt();
//             for (int i = l; i <= r; i++) {
//                 arr[i] += count;
//             }
//         }
//         for (int i = 1; i <= n; i++) {
//             System.out.print(arr[i] + " ");
//         }
//     }
// }