Cod sursa(job #3040408)

Utilizator lolismekAlex Jerpelea lolismek Data 29 martie 2023 20:47:06
Problema Matrice 2 Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.75 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <set>

#define pii pair <int, int>

using namespace std;

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

const int NMAX = 300;
const int QMAX = 2e4;

int n, q;
int mat[NMAX + 1][NMAX + 1];

struct Path{
    int x1, y1;
    int x2, y2;
    int ans;
}qs[QMAX + 1];

set <int> S[NMAX + 1][NMAX + 1];

bool cmp1(pii a, pii b){
    return mat[a.first][a.second] > mat[b.first][b.second];
}

namespace DSU{
    pii parent[NMAX + 1][NMAX + 1];

    pii Find(pii node){
        if(parent[node.first][node.second] == node){
            return node;
        }
        return parent[node.first][node.second] = Find(parent[node.first][node.second]);
    }

    void Join(pii node1, pii node2, int val){
        node1 = Find(node1);
        node2 = Find(node2);

        if(node1 == node2){
            return;
        }

        if((int)S[node1.first][node1.second].size() > (int)S[node2.first][node2.second].size()){
            swap(node1, node2);
        }

        for(int x : S[node1.first][node1.second]){
            if(S[node2.first][node2.second].find(x) != S[node2.first][node2.second].end()){
                if(qs[x].ans == -1){
                    qs[x].ans = val;
                }
            }
        }

        for(int x : S[node1.first][node1.second]){
            S[node2.first][node2.second].insert(x);
        }

        parent[node1.first][node1.second]= node2;
    }
}

// n, e, s, v:
int diri[] = {-1, 0, 1, 0};
int dirj[] = {0, -1, 0, 1};

bool inb(int i, int j){
    return (1 <= i && i <= n && 1 <= j && j <= n);
}

bool activ[NMAX + 1][NMAX + 1];

int main(){

    fin >> n >> q;

    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            fin >> mat[i][j];
            DSU::parent[i][j] = {i, j};
        }
    }

    for(int i = 1; i <= q; i++){
        fin >> qs[i].x1 >> qs[i].y1 >> qs[i].x2 >> qs[i].y2;
        S[qs[i].x1][qs[i].y1].insert(i);
        S[qs[i].x2][qs[i].y2].insert(i);
        qs[i].ans = -1;
    }

    vector <pii> cells;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            cells.push_back({i, j});
        }
    }
    sort(cells.begin(), cells.end(), cmp1);

    for(pii cell : cells){
        for(int dir = 0; dir < 4; dir++){
            int i = cell.first + diri[dir];
            int j = cell.second + dirj[dir];

            if(inb(i, j) && activ[i][j]){
                DSU::Join(cell, {i, j}, mat[cell.first][cell.second]);
            }
        }
        activ[cell.first][cell.second] = true;
    }

    for(int i = 1; i <= q; i++){
        fout << qs[i].ans << '\n';
    }

    return 0;
}