码迷,mamicode.com
首页 > 编程语言 > 详细

树状数组

时间:2020-09-18 03:56:02      阅读:37      评论:0      收藏:0      [点我收藏+]

标签:tin   rgs   ati   next   lse   array   数组   import   init   

import java.util.Scanner; /** * k 为尾部的0的个数 * C[i] = A[i - 2^k+1] + A[i - 2^k+2] + ... + A[i] */ public class TreeArray { private int size; private int arr[]; private int c[]; public TreeArray(int size) { this.size = size; this.arr = new int[size + 1]; this.c = new int[size + 1]; } private int lowbit(int x) { return x & (-x); } private void init(int i, int x) { this.arr[i] = x; add(i, x); } private void add(int i, int x) { arr[i] += x; while (i <= size) { c[i] += x; i += lowbit(i); } } private int sum(int i) { int s = 0; while (i > 0) { s += c[i]; i -= lowbit(i); } return s; } private void print() { for (int i = 1; i <= size; ++ i) { System.out.println(i + "--->" + arr[i]); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (true) { System.out.println("请输入数组大小"); int n = in.nextInt(); if (n <= 0) { break; } TreeArray treeArray = new TreeArray(n); System.out.println("请输入数组元素"); for (int i = 1; i <= n; ++ i) { int x = in.nextInt(); System.out.println(i + "--->" + x); treeArray.init(i, x); } while (true) { System.out.println("请输入指令"); String cmd = in.next(); if ("end".equals(cmd)) { break; } else if ("add".equals(cmd)) { System.out.println("请输入下标"); int i = in.nextInt(); System.out.println("请输入值"); int x = in.nextInt(); treeArray.add(i, x); treeArray.print(); } else if ("sum".equals(cmd)) { System.out.println("请输入下标"); int i = in.nextInt(); System.out.println("1-" + i + "的和 = " + treeArray.sum(i)); } else if ("print".equals(cmd)) { treeArray.print(); } } } } }

树状数组

标签:tin   rgs   ati   next   lse   array   数组   import   init   

原文地址:https://blog.51cto.com/tianyiya/2534270

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!