Cod sursa(job #1964243)

Utilizator GinguIonutGinguIonut GinguIonut Data 13 aprilie 2017 11:43:28
Problema Matrice 2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.43 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <string.h>

#define nMax 301
#define qMax 20001
#define elMax 90005
#define dirMax 4
#define pb push_back
#define mkp make_pair
#define x first
#define y second

using namespace std;

ifstream fin("matrice2.in");
ofstream fout("matrice2.out");

int n, nrQuery, nrEl, step, i, j, k;
int viz[nMax][nMax], P[elMax], Sol[qMax], P2[qMax], lin[elMax], col[elMax], Root[elMax], val[elMax], Query[qMax], poz[nMax][nMax], X1[qMax], X2[qMax], Y1[qMax], Y2[qMax];
const int dx[]={1, 0, -1, 0};
const int dy[]={0, 1, 0, -1};

bool cmpP(const int &f, const int &s)
{
    return val[f]>val[s];
}

bool cmpP2(const int &f, const int &s)
{
    return Query[f]>Query[s];
}

int getRoot(int node)
{
    return (Root[node]==node ? node : Root[node]=getRoot(Root[node]));
}

int main()
{
    fin>>n>>nrQuery;
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
        {
            poz[i][j]=++nrEl;
            lin[nrEl]=i, col[nrEl]=j;
            fin>>val[nrEl];
            P[nrEl]=nrEl;
        }
    }

    for(int i=1; i<=nrQuery; i++)
        fin>>X1[i]>>Y1[i]>>X2[i]>>Y2[i];
    sort(P+1, P+nrEl+1, cmpP);
    for(step=1; step<=val[P[1]]; step <<= 1);
    step >>= 1;

    for(; step; step >>=1 )
    {
        for(i=1; i<=nrQuery; i++)
        {
            Query[i]=Sol[i]+step;
            P2[i]=i;
        }
        sort(P2+1, P2+nrQuery+1, cmpP2);
        for(int i=1; i<=nrEl; i++)
        {
            Root[i]=i;
            viz[lin[i]][col[i]]=0;
        }

        for(i=1, j=1; i<=nrEl;)
        {
            for(; j<=nrQuery && Query[P2[j]]>val[P[i]]; j++)
                if(getRoot(poz[X1[P2[j]]][Y1[P2[j]]])==getRoot(poz[X2[P2[j]]][Y2[P2[j]]]))
                    Sol[P2[j]]+=step;
            for(k=i; i<=nrEl && val[P[k]]==val[P[i]]; i++)
            {
                int l=lin[P[i]], c=col[P[i]];
                viz[l][c]=1;
                for(int t=0; t<dirMax; t++)
                {
                    int newL=l+dx[t];
                    int newC=c+dy[t];
                    if(newL>=1 && newL<=n && newC>=1 && newC<=n && viz[newL][newC])
                        Root[getRoot(poz[newL][newC])]=Root[P[i]];
                }
            }
        }

        for(; j<=nrQuery; j++)
                Sol[P2[j]]+=step;
    }

    for(int i=1; i<=nrQuery; i++)
        fout<<Sol[i]<<'\n';
}