Cod sursa(job #3358804)

Utilizator alexlazuLazureanu Alexandru Ioan alexlazu Data 20 iunie 2026 16:31:38
Problema Plantatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <fstream>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 505;
int n, Q;
int mat[N][N];
// 3D array is perfectly sufficient for square-only queries and uses 10x less memory!
int rmq[10][N][N];

int main() {
    ifstream cin("plantatie.in");
    ofstream cout("plantatie.out");

    if (!cin) return 0; // Safety check for files

    cin >> n >> Q;

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> mat[i][j];
            rmq[0][i][j] = mat[i][j]; // Base case: squares of size 2^0 = 1
        }
    }

    int LOG = log2(n);

    // Build the 3D Sparse Table for squares
    for (int l = 1; l <= LOG; l++) {
        int len = 1 << (l - 1); // Size of the smaller sub-squares
        for (int i = 1; i + (1 << l) - 1 <= n; i++) {
            for (int j = 1; j + (1 << l) - 1 <= n; j++) {
                // A square of size 2^l is made of 4 overlapping squares of size 2^(l-1)
                rmq[l][i][j] = max({
                    rmq[l - 1][i][j],               // Top-Left
                    rmq[l - 1][i + len][j],         // Bottom-Left
                    rmq[l - 1][i][j + len],         // Top-Right
                    rmq[l - 1][i + len][j + len]    // Bottom-Right
                    });
            }
        }
    }

    while (Q--) {
        int x, y, k;
        cin >> x >> y >> k;

        int l = log2(k);
        int shift = k - (1 << l);

        // Query using 4 overlapping squares of size 2^l to cover the k x k square
        int ans = max({
            rmq[l][x][y],
            rmq[l][x + shift][y],
            rmq[l][x][y + shift],
            rmq[l][x + shift][y + shift]
            });

        cout << ans << "\n";
    }

    return 0;
}