Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1.  
  2. public class Segtree {
  3. static int[] total = new int[400000];
  4. static int[] left = new int[400000], right = new int[400000];
  5. static int[] data;
  6.  
  7. static void build(int l, int r, int node) {
  8. left[node] = l;
  9. right[node] = r;
  10. if (l + 1 == r) {
  11. total[node] = data[l];
  12. return;
  13. }
  14. int mid = (l + r) / 2;
  15. build(l, mid, node * 2);
  16. build(mid, r, node * 2 + 1);
  17.  
  18. total[node] = total[node * 2] + total[node * 2 + 1];
  19. }
  20.  
  21. static int query(int l, int r, int node) {
  22. // if current node is not inside interval
  23. if (left[node] >= r || right[node] <= l) {
  24. return 0;
  25. }
  26. // if current node is completely inside interval
  27. if (left[node] >= l && right[node] <= r) {
  28. return total[node];
  29. }
  30. // part of the thing
  31. return query(l, r, node * 2) + query(l, r, node * 2 + 1);
  32. }
  33.  
  34. static void update(int position, int value, int node) {
  35. // updated position is not inside current segment
  36. if (left[node] > position || right[node] <= position) {
  37. return;
  38. }
  39.  
  40. // is size 1
  41. if (left[node] + 1 == right[node]) {
  42. total[node] += value;
  43. return;
  44. }
  45.  
  46. // check children
  47. update(position, value, node * 2);
  48. update(position, value, node * 2 + 1);
  49.  
  50. // update itself
  51. total[node] = total[node * 2] + total[node * 2 + 1];
  52. }
  53.  
  54. public static void main(String[] args) {
  55. data = new int[] { 3, 2, 4, 1, 2, 7, 8, 5 };
  56. build(0, 8, 1);
  57. System.out.println(query(1, 6, 1));
  58. update(2, 10, 1);
  59. System.out.println(query(1, 5, 1));
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement