Cod sursa(job #2942064)

Utilizator AztecaVlad Tutunaru 2 Azteca Data 18 noiembrie 2022 21:02:36
Problema Matrice 2 Scor 35
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.64 kb
#include <bits/stdc++.h>

struct Edge {
  int u;
  int v;
  int cost;

  bool operator < (const Edge &b) {
    return cost > b.cost;
  }
};

struct Query {
  int u;
  int v;
  int id;

  int other(int node) {
    return u + v - node;
  }
};

using namespace std;

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

typedef long long ll;
const int N = (int) 3e2 + 7;
const int Q = (int) 2e4 + 7;
int a[N][N], mult[N * N], ret[Q];
map<pair<int, int>, int> queries[N * N];
Query questions[Q];
int n, q;

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

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

void init(int n) {
  for (int i = 1; i <= n; i++) {
    mult[i] = i;
  }
}

int root(int u) {
  if (u == mult[u]) {
    return u;
  }
  return mult[u] = root(mult[u]);
}

void unite(int u, int v, int cost) {
  u = root(u), v = root(v);
  if (u == v) return;

  if (queries[u].size() > queries[v].size()) {
    swap(u, v);
  }
  for (auto &it : queries[u]) {
    pair<int, int> qry = it.first;
    if (queries[v].count({questions[qry.second].other(qry.first), qry.second})) {
      ret[qry.second] = cost;
    }
  }
  for (auto &it : queries[v]) {
    queries[u][it.first] = 1;
  }
  queries[v].clear();

  mult[v] = u;
}

int main() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

  fin >> n >> q;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      fin >> a[i][j];
    }
  }
  for (int i = 1; i <= q; i++) {
    int x1, y1, x2, y2;
    fin >> x1 >> y1 >> x2 >> y2;
    questions[i] = {getnode(x1, y1), getnode(x2, y2), i};
  }
  for (int i = 1; i <= n; i++) {
    queries[questions[i].u][{questions[i].v, questions[i].id}] = 1;
    queries[questions[i].v][{questions[i].u, questions[i].id}] = 1;
  }
  vector<Edge> edges;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      if (inside(i - 1, j)) edges.push_back({getnode(i, j), getnode(i - 1, j), min(a[i][j], a[i - 1][j])});
      if (inside(i + 1, j)) edges.push_back({getnode(i, j), getnode(i + 1, j), min(a[i][j], a[i + 1][j])});
      if (inside(i, j - 1)) edges.push_back({getnode(i, j), getnode(i, j - 1), min(a[i][j], a[i][j - 1])});
      if (inside(i, j + 1)) edges.push_back({getnode(i, j), getnode(i, j + 1), min(a[i][j], a[i][j + 1])});
    }
  }
  sort(edges.begin(), edges.end());

  int m = edges.size();
  init(n * n);
  for (auto &edg : edges) {
    if (root(edg.u) != root(edg.v)) {
      unite(edg.u, edg.v, edg.cost);
    }
  }
  for (int i = 1; i <= q; i++) {
    fout << ret[i] << "\n";
  }
  return 0;
}