Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. package fenwicktree;
  2.  
  3. import java.io.*;
  4. import java.util.ArrayList;
  5. import java.util.StringTokenizer;
  6.  
  7. public class Main {
  8.  
  9. private int N;
  10. ArrayList<Integer> fenwick_tree = new ArrayList<Integer>();
  11.  
  12. public void addition(int k, int value) {
  13. for (; k < fenwick_tree.size(); k |= (k + 1)) {
  14. fenwick_tree.set(k, fenwick_tree.get(k) + value);
  15. }
  16. }
  17.  
  18. public int getQueryResult(int a, int b) {
  19. if (a == 0) {
  20. int sum = 0;
  21. for (; b >= 0; b = (b & (b + 1)) - 1) {
  22. sum += fenwick_tree.get(b);
  23. }
  24. return sum;
  25. } else {
  26. return getQueryResult(0, b) - getQueryResult(0, a - 1);
  27. }
  28. }
  29.  
  30. public int nextInt(String s) {
  31. return Integer.valueOf(s);
  32. }
  33.  
  34. public void run() {
  35. try {
  36. BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  37. StringTokenizer st;
  38. N = nextInt(bf.readLine());
  39. for (int i = 0; i <= N; i++) {
  40. fenwick_tree.add(0);
  41. }
  42. for (int i = 1; i <= N; i++) {
  43. addition(i, nextInt(bf.readLine()));
  44. }
  45. N = nextInt(bf.readLine());
  46. for (int i = 1; i <= N; i++) {
  47. st = new StringTokenizer(bf.readLine());
  48. System.out.println(getQueryResult(nextInt(st.nextToken()), nextInt(st.nextToken())));
  49. }
  50. } catch (IOException e) {
  51. }
  52. }
  53.  
  54. public static void main(String[] args) {
  55. new Main().run();
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement