Cod sursa(job #2349327)

Utilizator Alexa2001Alexa Tudose Alexa2001 Data 20 februarie 2019 13:19:16
Problema Matrice 2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

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

const int Nmax = 303, Qmax = 20005, lim = 1e6;

int n, q;
int a[Nmax*Nmax], ans[Qmax];

vector<int> mom[lim+2], vals[lim+2];
pair<int,int> b[Qmax];


int cell(int x, int y) { return (x-1) * n + y; }

namespace forest
{
    static int t[Nmax * Nmax];

    int boss(int x)
    {
        if(x == t[x]) return x;
        return t[x] = boss(t[x]);
    }

    bool connected(int x, int y)
    {
        return boss(x) == boss(y);
    }

    void reset()
    {
        int i;
        for(i=1; i<=n*n; ++i) t[i] = i;
    }

    void unite(int x, int y)
    {
        x = boss(x); y = boss(y);
        t[x] = y;
    }

    void baga(int x)
    {
        if(a[x - n] >= a[x]) unite(x-n, x);
        if(a[x-1] >= a[x]) unite(x-1, x);
        if(a[x+n] > a[x]) unite(x+n, x);
        if(a[x+1] > a[x]) unite(x+1, x);
    }
};

void check(int add)
{
    int i;
    for(i=1; i<=lim; ++i) mom[i].clear();
    for(i=1; i<=q; ++i)
        if(ans[i] + add <= lim) mom[ans[i] + add].push_back(i);

    forest :: reset();

    for(i=lim; i; --i)
    {
        for(auto it : vals[i]) forest :: baga(it);

        for(auto it : mom[i])
            if(forest :: connected(b[it].first, b[it].second)) ans[it] += add;
    }
}

int main()
{
    int i, j, x, X1, Y1, X2, Y2;

    fin >> n >> q;
    for(i=1; i<=n; ++i)
        for(j=1; j<=n; ++j)
        {
            fin >> x; a[cell(i,j)] = x;
            vals[x].push_back(cell(i, j));
        }

    for(i=1; i<=q; ++i)
    {
        fin >> X1 >> Y1 >> X2 >> Y2;
        b[i] = {cell(X1, Y1), cell(X2, Y2)};
    }

    for(i=20; i>=0; --i) check(1<<i);

    for(i=1; i<=q; ++i) fout << ans[i] << '\n';

    return 0;
}