AcWing 4878. 维护数组 java 树状数组 裸题

AcWing 4878. 维护数组

😎 树状数组实现动态维护区间和
⭐ java 传 数组 参数 是传地址(引用值)

import java.io.*;
import java.util.*;

public class Main
{
	static int N = 200010, n;
	static int[] tr1 = new int[N];
	static int[] tr2 = new int[N];
	static int[] d = new int[N];

	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

	static int lowbit(int x)
	{
		return -x & x;
	}

	static void add(int tr[], int x, int v)
	{
		for (int i = x; i <= n; i += lowbit(i))
			tr[i] += v;
	}

	static int query(int[] tr, int x)
	{
		int sum = 0;
		for (int i = x; i != 0; i -= lowbit(i))
			sum += tr[i];

		return sum;
	}

	public static void main(String[] args) throws IOException
	{
		String[] ss = in.readLine().split(" ");
		n = Integer.parseInt(ss[0]);
		int k = Integer.parseInt(ss[1]);
		int a = Integer.parseInt(ss[2]);
		int b = Integer.parseInt(ss[3]);
		int Q = Integer.parseInt(ss[4]);

		while (Q-- > 0)
		{
			String[] sss = in.readLine().split(" ");
			int t = Integer.parseInt(sss[0]);
			if (t == 1)
			{
				int x = Integer.parseInt(sss[1]);
				int y = Integer.parseInt(sss[2]);
				// 树状数组求 区间和 
				add(tr1, x, Math.min(d[x] + y, b) - Math.min(d[x], b));
				add(tr2, x, Math.min(d[x] + y, a) - Math.min(d[x], a));
				d[x] += y;
			} else
			{
				int p = Integer.parseInt(sss[1]);
				int res = query(tr1, p - 1) + query(tr2, n) - query(tr2, p + k - 1);
				System.out.println(res);
			}
		}
	}
}

posted @ 2023-03-25 23:00  兑生  阅读(24)  评论(0)    收藏  举报  来源
Live2D