Cod sursa(job #2327724)

Utilizator alexge50alexX AleX alexge50 Data 24 ianuarie 2019 20:47:58
Problema Plantatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.13 kb
/*
 * The idea of copyright didn't exist in ancient times when authors frequently
 * copied other authors at length in works of non-fiction. This practice was
 * useful, and is only way many authors' works have survived even in part.
 *      - Richard Stallman
 */

#include <iostream>
#include <array>
#include <fstream>
#include <numeric>

const int MAX_N = 500;
const int LOG_MAX_N = 9;

using rmqT = std::array<std::array<std::array<int, LOG_MAX_N + 1>, MAX_N + 1>, MAX_N + 1>;

std::array<int, MAX_N + 1> log;
rmqT rmqs;


template<typename F, typename T1, typename T2>
auto compose(F&& f, T1&& a, T2&& b) -> decltype(f(a, b))
{
    return f(a, b);
}

template<typename F, typename T, typename... Args>
T compose(F&& f, T arg, Args... args)
{
    return f(arg, compose(f, args...));
}


int rmqQuery(const rmqT &r, int x, int y, int k)
{
    int l = log[k];
   return compose(
               std::max<int>,
               r[x][y][l],
               r[x + k - (1 << l)][y][l],
               r[x][y + k - (1 << l)][l],
               r[x + k - (1 << l)][y + k - (1 << l)][l]
           );
}

template<size_t N>
std::array<int, N + 1> calculateLog()
{
    std::array<int, N + 1> l{};

    l[1] = 0;
    for(int i = 2; i <= N; i ++)
        l[i] = 1 + l[i / 2];

    return l;
}


int main()
{
    log = calculateLog<MAX_N>();
    std::ifstream fin("plantatie.in");
    int n, m;

    fin >> n >> m;
    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= n; j ++)
            fin >> rmqs[i][j][0];
    }

    for(int r = 0; r <= log[n]; r++)
        for(int i = 1; i + (1 << r) <= n; i++)
            for(int j = 1; j + (1 << r) <= n; j++)
                rmqs[i][j][r + 1] = compose(
                            std::max<int>,
                            rmqs[i][j][r],
                            rmqs[i + (1 << r)][j][r],
                            rmqs[i][j + (1 << r)][r],
                            rmqs[i + (1 << r)][j + (1 << r)][r]
                        );

    std::ofstream fout("plantatie.out");
    for(; m != 0; m --)
    {
        int i, j, k;
        fin >> i >> j >> k;

        fout << rmqQuery(rmqs, i, j, k) << '\n';
    }

    return 0;
}