Cod sursa(job #2763645)

Utilizator HabitusJovan Nikolic Habitus Data 15 iulie 2021 17:51:22
Problema Matrice 2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.52 kb
#include<bits/stdc++.h>
#define ios ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define dec(x, y) fixed << setprecision((y)) << (x)
#define xx first
#define yy second
#define srt(v) sort((v).begin(), (v).end())
#define srtr(v) sort((v).rbegin(), (v).rend())
#define pb push_back
#define popb pop_back
#define sz(a) (int)(a).size()
#define len(a) (int)(a).length()
#define mp make_pair
#define endl "\n"

using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int dx[]={-1, 0, 1, 0};
const int dy[]={0, 1, 0, -1};
int n, q;
int par[90010], h[90010];
int spar[90010], sh[90010];
int res[20010];
set<int> s[90010];
vector<pair<int, pii>> vr;
int dokle;
int mat[302][302];
int nadji(int x) {
    if(par[x]==x) return x;
    return par[x]=nadji(par[x]);
}
int snadji(int x) {
    if(spar[x]==x) return x;
    return spar[x]=snadji(spar[x]);
}
void merg(int a, int b) {
    a=nadji(a);
    b=nadji(b);
    int a1=snadji(a);
    int b1=snadji(b);
    if(a!=b) {
        if(h[a]<h[b]) swap(a, b);
        par[b]=a;
        h[a]+=h[b];
    }
    a=a1; b=b1;
    if(a!=b) {
        if(sh[a]<sh[b]) swap(a, b);
        spar[b]=a;
        for(auto it=s[b].begin(); it!=s[b].end(); ++it) {
            if(s[a].count(*it)) {
                s[a].erase(*it);
                --sh[a];
                res[*it]=dokle;
            }
            else {
                s[a].insert(*it);
                ++sh[a];
            }
        }
    }
}
inline bool post(int i, int j) {
    if(i<0 || i>=n || j<0 || j>=n) return false;
    return true;
}
int main() {
    ios;
    cin >> n >> q;
    for(int i=0; i<n; ++i) {
        for(int j=0; j<n; ++j) {
            cin >> mat[i][j];
            vr.pb({mat[i][j], {i, j}});
            par[i*n+j]=i*n+j;
            h[i*n+j]=1;
            spar[i*n+j]=i*n+j;
        }
    }
    srtr(vr);
    for(int i=0; i<q; ++i) {
        pii poc, kra;
        cin >> poc.xx >> poc.yy >> kra.xx >> kra.yy;
        --poc.xx; --poc.yy; --kra.xx; --kra.yy;
        s[poc.xx*n+poc.yy].insert(i);
        s[kra.xx*n+kra.yy].insert(i);
        sh[poc.xx*n+poc.yy]=1;
        sh[kra.xx*n+kra.yy]=1;
    }
    for(auto x:vr) {
        dokle=x.xx;
        for(int i=0; i<4; ++i) {
            if(post(x.yy.xx+dx[i], x.yy.yy+dy[i]) && mat[x.yy.xx+dx[i]][x.yy.yy+dy[i]]>=dokle) merg(x.yy.xx*n+x.yy.yy, (x.yy.xx+dx[i])*n+x.yy.yy+dy[i]);
        }
    }
    for(int i=0; i<q; ++i) cout << res[i] << endl;
    return 0;
}