Advertisement
newb_ie

SQRT Decompostion MIN / MAX

May 23rd, 2021
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 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. int64_t input[maxN];
  7. int64_t blocks[block_size];
  8.  
  9. int64_t query (int l,int r) {
  10.     int64_t min_ = LLONG_MAX;
  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) min_ = min(min_,input[i]);
  14.     } else {
  15.         int end = (block_l + 1) * block_size - 1;
  16.         for (int i = l; i <= end; ++i) min_ = min(min_,input[i]);
  17.         for (int i = block_l + 1; i < block_r; ++i) min_ = min(min_,blocks[i]);
  18.         for (int i = block_r * block_size; i <= r; ++i) min_ = min(min_,input[i]);
  19.     }
  20.     return min_;
  21. }
  22.  
  23. int main () {
  24.      ios::sync_with_stdio(false);
  25.      cin.tie(nullptr);
  26.      cout.tie(nullptr);
  27.      int T = 1;
  28.      //~ cin >> T;
  29.      for (int test_case = 1; test_case <= T; ++test_case) {
  30.          int n,k;
  31.          cin >> n >> k;
  32.          for (int i = 0; i < n; ++i) cin >> input[i];
  33.          for (int i = 0; i < block_size; ++i) blocks[i] = LLONG_MAX;
  34.          for (int i = 0; i < n; ++i) blocks[i / block_size] = min(blocks[i / block_size],input[i]);
  35.          if (k == 1) {
  36.              cout << query(0,n - 1) << '\n';
  37.          } else if (k == 2) {
  38.              int64_t max_ = LLONG_MIN;
  39.              for (int i = 0; i < n - 1; ++i) {
  40.                  int l1 = 0,r1 = i;
  41.                  int l2 = i + 1,r2 = n - 1;
  42.                  max_ = max(max_,max(query(l1,r1),query(l2,r2)));
  43.              }
  44.              cout << max_ << '\n';
  45.          } else {
  46.              int64_t max_ = LLONG_MIN;
  47.              for (int i = 0; i < n; ++i) max_ = max(input[i],max_);
  48.              cout << max_ << '\n';
  49.          }
  50.      }
  51.      //~ cerr << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement