题目链接:1.肖恩的投球游戏 - 蓝桥云课 (lanqiao.cn)
前缀和:
package lanqiao;
import java.util.Arrays;
import java.util.Scanner;
/**
* 2023/11/29
* 前缀和问题
*/
public class lanqiao3693_肖恩的投球游戏 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();//球筐数
int q = scan.nextInt();//操作数
int[] a = new int[n];//每个筐里的原始球数
for (int i = 0; i < n; i++)
a[i] = scan.nextInt();
int[] pre = new int[n + 1];//前缀和
while (q-- > 0) {
int l = scan.nextInt() - 1;//索引要比我输入的球筐顺序少1
int r = scan.nextInt() - 1;
int c = scan.nextInt();
pre[l] += c;//在l处加c,则l-r处的前缀和都加c
pre[r + 1] -= c;//在r+1处减c,则把r+1后面的前缀和挪去c
}
for (int i = 1; i < n; i++) {
pre[i] = pre[i] + pre[i - 1];//求前缀和
}
for (int i = 0; i < n; i++)
a[i] += pre[i];//在前缀和里加上原始的球数
for (int i = 0; i < n; i++)
System.out.println("a["+i+"] = " + a[i]);
}
}
5 3
7 5 7 7 3
1 5 3
1 5 2
4 4 4
a[0] = 12
a[1] = 10
a[2] = 12
a[3] = 16
a[4] = 8
进程已结束,退出代码为 0