Cod sursa(job #835258)

Utilizator cdascaluDascalu Cristian cdascalu Data 15 decembrie 2012 21:34:41
Problema Plantatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.74 kb
#include <stdio.h>
#define Nmax 501
#define LG_MAX 10
using namespace std;

int N,M,mat[Nmax][Nmax],RMQ[LG_MAX][Nmax][Nmax],X,Y,K,put[Nmax];

FILE*f;
FILE*g;

void init()
{
    f = fopen("plantatie.in","r");
    g = fopen("plantatie.out","w");
    fscanf(f,"%d%d",&N,&M);
}
void read_matrix()
{
    int i,j,x;
    for(i=1;i<=N;++i)
         for(j=1;j<=N;++j)
             fscanf(f,"%d",&mat[i][j]);
}
int maxim(int a,int b,int c,int d)
{
    if(a>=b && a>=c && a>=d)
        return a;
    if(b>=c && b>=d)
        return b;
    if(c>=d)
        return c;
    return d;
}
void get_rmq()
{
    int i,j,p,a,b,c,d,half;

    for(i=1,p=0;i<=N;++i)
    {
        if(1 << (p+1) <= i)
            ++p;
        put[i] = p;
    }

    for(i=1;i<=N;++i)
        for(j=1;j<=N;++j)
            RMQ[0][i][j] = mat[i][j];

    for(p=1; (1<<p) <= N; ++p)
    {
        half    = 1<<(p-1);
        for(i=1;i + (1<<p) - 1 <= N;++i)
            for(j=1; j + (1<<p) - 1 <= N;++j)
            {
                a       = RMQ[p-1][i][j];
                b       = RMQ[p-1][i + half][j];
                c       = RMQ[p-1][i][j + half];
                d       = RMQ[p-1][i+half][j+half];

                RMQ[p][i][j] = maxim(a,b,c,d);
            }
    }
}
void get_query()
{
    fscanf(f,"%d%d%d",&X,&Y,&K);
}
int query(int x,int y,int k)
{
    int a,b,c,d,p;
    p       = 1<<put[k];
    a       = RMQ[ put[k] ][x][y];
    b       = RMQ[ put[k] ][x+k-p][y];
    c       = RMQ[ put[k] ][x][y+k-p];
    d       = RMQ[ put[k] ][x+k-p][y+k-p];
    return maxim(a,b,c,d);
}
void solve()
{
    while(M--)
    {
        get_query();
        fprintf(g,"%d\n",query(X,Y,K));
    }
}
int main()
{
    init();
    read_matrix();
    get_rmq();
    solve();
    fclose(f);
    fclose(g);
    return 0;
}