Advertisement
Saleh127

Light OJ 1081 / 2D Sparse Table

Jan 4th, 2023
997
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. /**
  2.  
  3.     2D range queries - Sparse table
  4.     Author :: Umnik
  5.  
  6. **/
  7.  
  8.  
  9. /***
  10.  created: 2023-01-05-02.09.28
  11. ***/
  12.  
  13. #include <bits/stdc++.h>
  14. #include <ext/pb_ds/assoc_container.hpp>
  15. #include <ext/pb_ds/tree_policy.hpp>
  16. using namespace std;
  17. using namespace __gnu_pbds;
  18. template<typename U> using ordered_set=tree<U, null_type,less<U>,rb_tree_tag,tree_order_statistics_node_update>;
  19. #define ll long long
  20. #define all(we) we.begin(),we.end()
  21. #define test int tt; cin>>tt; for(int cs=1;cs<=tt;cs++)
  22. #define nl '\n'
  23.  
  24. const int INF = (int)1e9;
  25. const int LOG = 11;
  26. const int N = 1010;
  27. int p2[N];
  28. vector<vector<int>> sparse[LOG];
  29.  
  30. int getMax(int x, int y, int d)
  31. {
  32.     int k = p2[d];
  33.     int s = d - (1 << k);
  34.     return max(max(sparse[k][x][y], sparse[k][x + s][y]), max(sparse[k][x][y + s], sparse[k][x + s][y + s]));
  35. }
  36.  
  37. int main()
  38. {
  39.     ios_base::sync_with_stdio(0);
  40.     cin.tie(0);
  41.     cout.tie(0);
  42.  
  43.  
  44.     for (int i = 2; i < N; i++)
  45.     {
  46.         p2[i] = p2[i / 2] + 1;
  47.     }
  48.  
  49.     test
  50.     {
  51.         ll n,m,i,j,k,l;
  52.  
  53.         cin>>n>>m;
  54.  
  55.         for (k = 0; k < LOG; k++)
  56.         {
  57.             sparse[k] = vector<vector<int>>(n, vector<int>(n, 0));
  58.         }
  59.         for (i = 0; i < n; i++)
  60.         {
  61.             for (j = 0; j < n; j++)
  62.             {
  63.                 cin>>sparse[0][i][j];
  64.             }
  65.         }
  66.         for (k = 0; k < LOG - 1; k++)
  67.         {
  68.             for (i = 0; i + (1 << (k + 1)) <= n; i++)
  69.             {
  70.                 for (j = 0; j + (1 << (k + 1)) <= n; j++)
  71.                 {
  72.                     sparse[k + 1][i][j] = max(max(sparse[k][i][j], sparse[k][i + (1 << k)][j]), max(sparse[k][i][j + (1 << k)], sparse[k][i + (1 << k)][j + (1 << k)]));
  73.                 }
  74.             }
  75.         }
  76.  
  77.         cout<<"Case "<<cs<<":"<<nl;
  78.  
  79.         while(m--)
  80.         {
  81.             cin>>i>>j>>k;
  82.             i--,j--;
  83.             cout<<getMax(i,j,k)<<nl;
  84.         }
  85.  
  86.     }
  87.     return 0;
  88. }
  89.  
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement