Cod sursa(job #2715766)

Utilizator Iulia25Hosu Iulia Iulia25 Data 4 martie 2021 10:28:16
Problema Matrice 2 Scor 35
Compilator cpp-64 Status done
Runda simularedelacasi1 Marime 1.79 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <unordered_map>

using namespace std;

ifstream cin ("matrice2.in");
ofstream cout ("matrice2.out");


struct idk  {
  int cost, x, y;
};

struct query  {
  int x, y, i;
};

bool cmp(idk x, idk y)  {
  return x.cost > y.cost;
}

int n, q;
int tata[90005], ans[20005];
int a[305][305];

vector <query> v, v2;
vector <idk> muchii;
unordered_map <int, int> m[90005];

inline int nr(int l, int c)  {
  return (l - 1) * n + c;
}

int find_daddy(int nod) {
  int aux = nod;
  while (tata[nod] > 0)
    nod = tata[nod];
  while (tata[aux] > 0) {
    int aux2 = tata[aux];
    tata[aux] = nod;
    aux = aux2;
  }
  return nod;
}

void Union(int x, int y)  {
  x = find_daddy(x);
  y = find_daddy(y);
  if (tata[x] > tata[y])
    swap(x, y);
  tata[x] += tata[y];
  tata[y] = x;
}

int main()  {
  cin >> n >> q;
  for (int i = 1; i <= n; ++i)  {
    for (int j = 1; j <= n; ++j)  {
      cin >> a[i][j];
      tata[nr(i, j)] = -1;
    }
  }
  for (int i = 1; i <= n; ++i)  {
    for (int j = 1; j <= n; ++j)  {

      if (j > 1)  {
        muchii.push_back({min(a[i][j], a[i][j - 1]), nr(i, j), nr(i, j - 1)});
      }

      if (i > 1)  {
        muchii.push_back({min(a[i][j], a[i - 1][j]), nr(i, j), nr(i - 1, j)});
      }
    }
  }
  sort (muchii.begin(), muchii.end(), cmp);
  int x1, y1, x2, y2;
  for (int i = 1; i <= q; ++i)  {
    cin >> x1 >> y1 >> x2 >> y2;
    v.push_back({nr(x1, y1), nr(x2, y2), i});
  }
  for (auto it : muchii)  {
    if (find_daddy(it.x) == find_daddy(it.y))
      continue;
    Union(it.x, it.y);
    v2 = v;
    v.clear();
    for (auto p : v2) {
      if (find_daddy(p.x) == find_daddy(p.y)) {
        ans[p.i] = it.cost;
      }
      else v.push_back(p);
    }
  }
  for (int i = 1; i <= q; ++i)
    cout << ans[i] << '\n';
	return 0;
}