Cod sursa(job #2893948)

Utilizator pedrosanchez2pedro sanchez pedrosanchez2 Data 26 aprilie 2022 21:36:01
Problema Plantatie Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.21 kb
#include <iostream>
#include <fstream>
#include <array>
#include <math.h>

using namespace std;

/*ifstream in("input.txt");
ofstream out("output.txt");*/

ifstream in("plantatie.in");
ofstream out("plantatie.out");

struct P
{
    int row, col;
    P(int row, int col) : row(row), col(col) {}
    P() = default;
};

P mat[501][501][9];
int a[501][501],n,m;

P getMax(P e, P b, P c, P d)
{
    int mx = a[e.row][e.col];
    P res = e;
    if (a[b.row][b.col] > mx)
    {
        mx = a[b.row][b.col];
        res = b;
    }
     if (c.row != -1 && c.col != -1 && a[c.row][c.col] > mx)
    {
        mx = a[c.row][c.col];
        res = c;
    }
     if (d.row != -1 && d.col != -1 && a[d.row][d.col] > mx)
    {
        mx = a[d.row][d.col];
        res = d;
    }
    return res;
}

void precompute_max(){
    for (int i = 0 ; (1<<i) <= n; i += 1){
            for (int x = 0 ; x + (1<<i) -1 < n; x+= 1){
                for (int y = 0 ;  y + (1<<i) -1 < n; y+= 1){
                    if (i == 0)
                        mat[x][y][i] = P(x, y); // store x, y
                    else 
                        mat[x][y][i] = getMax(mat[x][y][i-1], mat[x + (1<<(i-1))][y][i-1], mat[x][y+(1<<(i-1))][i-1], mat[x + (1<<(i-1))][y+(1<<(i-1))][i-1]);
                    // cout << "from i="<<x<<" j="<<y<<" of length="<<(1<<i)<<" and length="<<(1<<j) <<"max is: " << M[x][y][i][j] << endl;
                }
        }
    }
}

int main()
{
    in >> n >> m;
    //cout << n << " " << m << endl;
    int lg[501];
    lg[1] = 0;
    for (int i = 2; i < 501; ++i)
        lg[i] = lg[i / 2] + 1;
    for (int i = 0; i < n; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            in >> a[i][j];
           // cout << a[i][j] << " ";
        }
       // cout << endl;
    }
    precompute_max();
    for (int i = 0; i < m; ++i)
    {
        int x, y, len;
        in >> x >> y >> len;
        //cout << row << " " << col << " " << len << endl;
        --x, --y;
        int k = lg[len];
        int l = lg[len];
        int x1 = x + len - 1;
        int y1 = y + len - 1;
        P ans = getMax(mat[x][y][k], mat[x1 - (1<<k) + 1][y][k], mat[x][y1 - (1<<l) + 1][k], mat[x1 - (1<<k) + 1][y1 - (1<<l) + 1][k]);
        out << a[ans.row][ans.col] << endl;
    }
}