树状数组和线段树模板

树状数组:支持单点修改,和前缀求和。

1264.动态求连续区间和

给定 nn 个数组成的一个数列,规定有两种操作,一是修改某个元素,二是求子数列[a,b]的连续和。

输入格式

第一行包含两个整数 n 和 m,分别表示数的个数和操作次数。

第二行包含 n 个整数,表示完整数列。

接下来 m 行,每行包含三个整数 k,a,bk,a,b (k=0,表示求子数列[a,b][a,b]的和;k=1,表示第 a 个数加 b)。

数列从 11 开始计数。

输出格式

输出若干行数字,表示 k=0k=0 时,对应的子数列 [a,b][a,b] 的连续和。

数据范围

1≤n≤1000001≤n≤100000,
1≤m≤1000001≤m≤100000,
1≤a≤b≤n

输入样例:
10 5
1 2 3 4 5 6 7 8 9 10
1 1 5
0 1 3
0 4 8
1 7 5
0 4 8
输出样例:
11
30
35

树状数组和线段树模板题:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Stack;

public class Main {
   
	static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	static Scanner sc = new Scanner(System.in);
	static final int N = (int)1e5 + 100;
	static int[] a = new int[N], tr = new int[N];
	static int n;
	private static int lowbit(int x) {
   
		return x & (-x);
	}
	
	private static void add(int x, int y) {
   
		for(int i = x; i <= n; i += lowbit(i)) {
   
			tr[i] += y;
		}
	}
	
	private static int query(int x) {
   
		int res = 0;
		for(int i = x; i > 0; i -= lowbit(i)) {
   
			res += tr[i];
		}
		return res;
	}
	public static void main(String[] args) {
   
		n = sc.nextInt();
		int m = sc.nextInt();
		for(int i = 1; i <= n; i++)a[i] = sc.nextInt();
		for(int i = 1; i <= n; i++)add(i,a[i]);
		
		for(int i = 1; i <= m; i++) {
   
			int ch = sc.nextInt(), a = sc.nextInt(), b = sc.nextInt();
			if(ch == 1) {
   
				add(a,b);
			}else {
   
				int res = query(b) - query(a - 1);
				System.out.println(res);
			}
		}
	}
}

线段树:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Scanner;
import java.util.Stack;



public class Main {
   
	static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	static Scanner sc = new Scanner(System.in);
	static final int  N = 100100;
	static int[] w = new int[N];
	static Node[] tr = new Node[4 * N];
	public static void main(String[] args) throws IOException {
   
		String[] input = bf.readLine().split(" ");
		int n = Integer.parseInt(input[0]);
		int m = Integer.parseInt(input[1]);
		
		String[] str = bf.readLine().split(" ");
		for(int i = 1; i <= n; i++) w[i] = Integer.parseInt(str[i - 1]);
		
		build(1,1,n);
		
		while(m-- > 0) {
   
			String[] s3 = bf.readLine().split(" ");
            int k = Integer.parseInt(s3[0]);
            int x = Integer.parseInt(s3[1]);
            int y = Integer.parseInt(s3[2]);
            
            if(k == 0)System.out.println(query
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值