Alex_tz307

RMQ 2D

Aug 16th, 2021
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int MAXN = 212;
  6. const int LGMAX = 8;
  7. int n, lg2[MAXN], rmq[LGMAX][LGMAX][MAXN][MAXN];
  8.  
  9. int query(int x1, int y1, int x2, int y2) {
  10.   int h1 = lg2[x2 - x1], h2 = lg2[y2 - y1];
  11.   return min({rmq[h1][h2][x1][y1], rmq[h1][h2][x2 - (1 << h1) + 1][y1],
  12.               rmq[h1][h2][x1][y2 - (1 << h2) + 1], rmq[h1][h2][x2 - (1 << h1) + 1][y2 - (1 << h2) + 1]});
  13. }
  14.  
  15. void test_case() {
  16.   cin >> n;
  17.   for (int i = 1; i <= n; ++i)
  18.     for (int j = 1; j <= n; ++j)
  19.         cin >> rmq[0][0][i][j];
  20.   for (int i = 2; i < MAXN; ++i)
  21.     lg2[i] = lg2[i >> 1] + 1;
  22.   for (int h1 = 0; h1 < LGMAX; ++h1)
  23.     for (int h2 = 0; h2 < LGMAX; ++h2)
  24.       if (h1 > 0 || h2 > 0)
  25.         for (int i = 1; i <= n; ++i)
  26.           for (int j = 1; j <= n; ++j)
  27.             if (i + (1 << h1) - 1 <= n && j + (1 << h2) - 1 <= n)
  28.               rmq[h1][h2][i][j] = query(i, j, i + (1 << h1) - 1, j + (1 << h2) - 1);
  29. }
  30.  
  31. int main() {
  32.   ios_base::sync_with_stdio(false);
  33.   cin.tie(nullptr);
  34.   cout.tie(nullptr);
  35.   int T = 1;
  36.   for (int tc = 0; tc < T; ++tc)
  37.     test_case();
  38.   return 0;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment