Cod sursa(job #1681311)

Utilizator preda.andreiPreda Andrei preda.andrei Data 9 aprilie 2016 13:04:54
Problema Plantatie Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.74 kb
#include <iostream>
#include <cstdio>

using namespace std;

int mat[501][501];
int maxim[501][501][12];

int plantatieMax(int l, int c1, int c2);

int main()
{
    FILE *fin = fopen("plantatie.in", "r");
    FILE *fout = fopen("plantatie.out", "w");

    int n, t, x, y, lat, rez, col1, col2;

    fscanf(fin, "%d%d", &n, &t);
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= n; ++j){
            fscanf(fin, "%d", &mat[i][j]);
            maxim[i][j][0] = j;
        }
    }

    for(int i = 1; i <= n; ++i){
        //fprintf(fout, "\n%d\n", i);
        for(int j = n; j >= 1; --j){
            //fprintf(fout, "%d: ", j);
            for(int k = 1; j + (1 << (k - 1)) <= n; ++k){
                if(mat[i][maxim[i][j][k - 1]] >= mat[i][maxim[i][j + (1 << (k - 1))][k - 1]])
                    maxim[i][j][k] = maxim[i][j][k - 1];
                else maxim[i][j][k] = maxim[i][j + (1 << (k - 1))][k - 1];
                //fprintf(fout, "%d ", maxim[i][j][k]);
            }
            //fprintf(fout, "\n");
        }
    }

    while(t--){
        fscanf(fin, "%d%d%d", &x, &y, &lat);
        rez = 0;

        col1 = y;
        col2 = y + lat - 1;

        for(int i = x; i < x + lat; ++i){
            y = plantatieMax(i, col1, col2);
            if(y > rez)
                rez = y;
        }

        fprintf(fout, "%d\n", rez);
    }


    return 0;
}

int plantatieMax(int l, int c1, int c2){
    int lung = c2 - c1 + 1, k = 0, n1, n2, rez = 0;

    while((1 << k) < lung)
        ++k;

    if(1 << k == lung)
        return mat[l][maxim[l][c1][k]];

    --k;
    n1 = mat[l][maxim[l][c1][k]];
    n2 = mat[l][maxim[l][c2 - (1 << k) + 1][k]];

    return (n1 > n2) ? n1 : n2;
}