Advertisement
dipBRUR

2

Nov 19th, 2017
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.71 KB | None | 0 0
  1. Binary Indexed Tree
  2. * Point Update & Range Query | * Range Update & Range Query | * Inversion Count
  3. int res[MAXN], N; | int res_1[MAXN]; // BIT 1 | 1. UPDATE FUNCTION
  4. void UPDATE(int idx, int val) { | void UPDATE_1(int idx, int val) { | 2. READ FUNCTION
  5. while (idx <= N) { | while (idx <= N) { | // map all number w.r first index
  6. res[idx] += val; | res_1[idx] += val; | for (int i = 0; i < N; i++) {
  7. idx += (idx & -idx); | idx += (idx & -idx); | cin >> A[i];
  8. } | } | B[i] = A[i];
  9. } | } | }
  10. int READ(int idx) { | int READ_1(int idx) { | sort(B, B+N);
  11. int sum = 0; | int sum = 0; | for (int i = 0; i < N; i++) {
  12. while (idx > 0) { | while (idx > 0) { | int rank = lower_bound(B, B+N, A[i])-B;
  13. sum += res[idx]; | sum += res_1[idx]; | rank += 1; // BIT is 1 indexed
  14. idx -= (idx & -idx); | idx -= (idx & -idx); | A[i] = rank;
  15. } | } | }
  16. return sum; | return sum; | ll inversion = 0;
  17. } | } | for (int i = N-1; i >= 0; i--) {
  18. int QUERY(int l, int r) { | int res_2[MAXN]; // BIT 2 | int x = READ(A[i]-1);
  19. return READ(r) - READ(l-1); | void UPDATE_2(int idx, int val) { | inversion += x;
  20. } | while (idx <= N) { | update(A[i]);
  21. * Range Update & Point Query | res_2[idx] += val; | }
  22. void UPDATE(int idx, int val) { | idx += (idx & -idx); |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
  23. while (idx <= N) { | }
  24. res[idx] += val; | }
  25. idx += (idx & -idx); | int READ_2(int idx) {
  26. } | int sum = 0;
  27. } | while (idx > 0) {
  28. void RANGE_UPDATE(int l, int r, int val) {| sum += res_2[idx];
  29. UPDATE(l, val); | idx -= (idx & -idx);
  30. UPDATE(r+1, -val); | }
  31. } | return sum;
  32. int QUERY(int idx) { | }
  33. int sum = 0; | void RANGE_UPDATE(int l, int r, int val) {
  34. while (idx > 0) { | UPDATE_1(l, val); UPDATE_1(r+1, -val);
  35. sum += res[idx]; | UPDATE_2(l, val*(l-1)); UPDATE_2(r+1, -val*r);
  36. idx -= (idx & -idx); | }
  37. } | int RANGE_QUERY(int l, int r) {
  38. return sum; | int sum_r = READ_1(r)*r - READ_2(r);
  39. } | int sum_l = READ_1(l-1)*(l-1) - READ_2(l-1);
  40. | return sum_r - sum_l;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement