Cod sursa(job #2784045)

Utilizator MateiAruxandeiMateiStefan MateiAruxandei Data 15 octombrie 2021 17:15:00
Problema Matrice 2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.73 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX(305);
map<int, int> mp;
vector<pair<int, int> > vec[NMAX * NMAX];
int cnt, cnvB[NMAX * NMAX], x1, y1, x2, y2, n, q, nrP, mat[NMAX][NMAX], aux[NMAX][NMAX];
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};

class DSU{
public:
    vector<int> p, rnk;
    stack<int> st;
    DSU(){}
    void initialize(int n){
        p.resize(n + 1), rnk.resize(n + 1);
        for(int i = 1; i <= n; ++i){
            p[i] = i;
            rnk[i] = 0;
        }
    }
    int findR(int x){
        if(x == p[x])
            return x;
        return findR(p[x]);
    }
    void Unite(int x, int y){
        x = findR(x);
        y = findR(y);
        if(x == y)
            return;
        if(rnk[x] > rnk[y])
            swap(x, y);
        st.push(x);
        p[x] = y;
        rnk[y] += rnk[x];
    }
    void Rollback(){
        while(!st.empty()){
            int x = st.top();
            st.pop();
            rnk[p[x]] -= rnk[x];
            p[x] = x;
        }
    }
};
DSU Arb;

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

inline bool check(int limJ)
{
    for(int i = limJ; i <= cnt; ++i)
        for(auto it: vec[i])
        {
            aux[it.first][it.second] = nrP;
            for(int k = 0; k < 4; ++k)
            {
                int newX = it.first + dx[k];
                int newY = it.second + dy[k];
                if(aux[newX][newY] == nrP)
                    Arb.Unite(getId(it.first, it.second), getId(newX, newY));
            }
        }
    if(Arb.findR(getId(x1, y1)) == Arb.findR(getId(x2, y2)))
        return 1;
    return 0;
}

int main()
{
    fin >> n >> q;

    set<int> s;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
        {
            fin >> mat[i][j];
            s.insert(mat[i][j]);
        }
    for(auto it: s)
    {
        mp[it] = ++cnt;
        cnvB[cnt] = it;
    }
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
        {
            mat[i][j] = mp[mat[i][j]];
            vec[mat[i][j]].push_back({i, j});
        }

    Arb.initialize(n * n);
    nrP = 0;
    for(int i = 1; i <= q; ++i)
    {
        fin >> x1 >> y1 >> x2 >> y2;

        int st = 1;
        int dr = cnt;
        int best = 0;
        while(st <= dr)
        {
            int mij = (st + dr) >> 1;
            ++nrP;
            if(check(mij))
            {
                best = mij;
                st = mij + 1;
            }
            else dr = mij - 1;
            Arb.Rollback();
        }
        fout << cnvB[best] << '\n';
    }
    return 0;
}