Advertisement
newb_ie

SQRT Decompostion

May 23rd, 2021
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int maxN = 2 * 1e5 + 100;
  5. const int block_size = 450;
  6. int input[maxN];
  7. int blocks[block_size];
  8.  
  9. int query (int l,int r) {
  10.     int sum = 0;
  11.     int block_l = l / block_size,block_r = r / block_size;
  12.     if (block_l == block_r) {
  13.         for (int i = l; i <= r; ++i) sum += input[i];
  14.     } else {
  15.         int end = (block_l + 1) * block_size - 1;
  16.         for (int i = l; i <= end; ++i) sum += input[i];
  17.         for (int i = block_l + 1; i < block_r; ++i) sum += blocks[i];
  18.         for (int i = block_r * block_size; i <= r; ++i) sum += input[i];
  19.     }
  20.     return sum;
  21. }
  22.  
  23. void init (int n) {
  24.     for (int i = 0; i < n; ++i) blocks[i / block_size] += input[i];
  25. }
  26.  
  27. void test () {
  28.     int n = 15000;
  29.     for (int i = 0; i < n; ++i) input[i] = rand() % 15000 + 10;
  30.     init(n);
  31.     int q = 200;
  32.     for (int i = 1; i <= q; ++i) {
  33.         int l = rand() % 15000;
  34.         int r = rand() % 15000;
  35.         if (l > r) continue;
  36.         int sum = 0;
  37.         for (int i = l; i <= r; ++i) sum += input[i];
  38.         assert(sum == query(l,r));
  39.     }
  40. }
  41.  
  42. int main () {
  43.      ios::sync_with_stdio(false);
  44.      cin.tie(nullptr);
  45.      cout.tie(nullptr);
  46.      int T = 1;
  47.      //~ cin >> T;
  48.      for (int test_case = 1; test_case <= T; ++test_case) {
  49.          int n,q;
  50.          cin >> n >> q;
  51.          for (int i = 0; i < n; ++i) cin >> input[i];
  52.          for (int i = 0; i < n; ++i) blocks[i / block_size] += input[i];
  53.          for (int i = 1; i <= q; ++i) {
  54.              int l,r;
  55.              cin >> l >> r;
  56.              --l,--r;
  57.              cout << query(l,r) << '\n';
  58.          }
  59.      }
  60.      //~ cerr << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement