Cod sursa(job #3166376)

Utilizator PalcPalcu Stefan Palc Data 8 noiembrie 2023 17:45:54
Problema Matrice 2 Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.64 kb
#include <bits/stdc++.h>
using namespace std;

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

struct vrajeala
{
    int x, y, val;
    bool operator <(const vrajeala A) const
    {
        return A.val < val;
    }
};

int n, Q;
int a[305][305], t[90005], sol[20005];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
bitset<90005> viz;
vector<vrajeala> val;
set<pair<int, int>> qr[90005];

int Cod(int i, int j)
{
    return (i - 1) * n + j;
}

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

int Find(int x)
{
    int y, rad = x;
    while (t[rad] != 0)
        rad = t[rad];
    while (x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}

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

int main()
{
    int x, y, x_st, y_st, x_fn, y_fn, rx, ry;
    int xx, yy;
    fin >> n >> Q;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
        {
            fin >> a[i][j];
            val.push_back({i, j, a[i][j]});
        }
    for (int i = 1; i <= Q; i++)
    {
        fin >> x_st >> y_st >> x_fn >> y_fn;
        x = Cod(x_st, y_st);
        y = Cod(x_fn, y_fn);
        qr[x].insert({y, i});
        qr[y].insert({x, i});
    }
    sort(val.begin(), val.end());
    for (auto f : val)
    {
        x = Cod(f.x, f.y);
        viz[x] = 1;
        for (int k = 0; k <= 3; k++)
        {
            xx = f.x + dx[k];
            yy = f.y + dy[k];
            y = Cod(xx, yy);
            if (Inauntru(xx, yy) && viz[y] == 1)
            {
                x = Find(x);
                y = Find(y);
                if (x != y)
                {
                    if (qr[x].size() < qr[y].size())
                        swap(x, y);
                    for (auto e : qr[y])
                    {
                        if (Find(e.first) == x)
                        {
                            sol[e.second] = min(a[f.x][f.y], a[xx][yy]);
                            cout << e.first << "->" << Find(e.first) << " " << x << "\n";
                            cout << f.x << " " << f.y << " " << xx << " " << yy << "\n";
                        }
                        else qr[x].insert(e);
                    }
                    Union(x, y);
                    qr[y].clear();
                }
            }
        }
    }
    for (int i = 1; i <= Q; i++)
        fout << sol[i] << "\n";
    return 0;
}
/**
        /\
       /xx\
      /xxxx\
     /xx/\xx\
    /xx//\\xx\
   /xx//xx\\xx\
  /xx//xxxx\\xx\
 /xx//xx/\xx\\xx\
/xx//xx/xx\xx\\xx\
\xx\\xx\xx/xx//xx/
 \xx\\xx\/xx//xx/
  \xx\\xxxx//xx/
   \xx\\xx//xx/
    \xx\\//xx/
     \xx\/xx/
      \xxxx/
       \xx/
        \/
*/