Cod sursa(job #2675937)

Utilizator lucametehauDart Monkey lucametehau Data 22 noiembrie 2020 22:31:49
Problema Matrice 2 Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.89 kb
#include <bits/stdc++.h>

using namespace std;

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

struct Query {
  int x1, y1, x2, y2, ind, ans;
  bool operator < (const Query &other) const {
    return ans > other.ans;
  }
} a[20005];

struct Elem {
  int val, x, y;
  bool operator < (const Elem &other) const {
    return val > other.val;
  }
};

int n, q;

int v[90005], t[90005], sz[90005];
Elem w[90005];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};

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

int tata(int x) {
  if(t[x] == x)
    return x;
  t[x] = tata(t[x]);
  return t[x];
}

void join(int x, int y) {
  if(x == y)
    return;
  if(sz[x] > sz[y])
    t[y] = x, sz[x] += sz[y];
  else
    t[x] = y, sz[y] += sz[x];
}

bool comp(Query a, Query b) {
  return a.ind < b.ind;
}

int main() {
  in >> n >> q;
  for(int i = 1; i <= n; i++) {
    for(int j = 1; j <= n; j++) {
      int c = cod(i, j);
      in >> v[c];
      w[c] = {v[c], i, j};
    }
  }
  for(int i = 1; i <= q; i++)
    in >> a[i].x1 >> a[i].y1 >> a[i].x2 >> a[i].y2, a[i].ind = i;
  sort(w + 1, w + n * n + 1);
  for(int p = (1 << 19); p; p >>= 1) {
    sort(a + 1, a + q + 1);
    int j = 1;
    for(int i = 1; i <= n * n; i++)
      t[i] = i, sz[i] = 1;
    for(int i = 1; i <= q; i++) {
      int val = a[i].ans + p;
      while(w[j].val >= val && j <= n * n) {
        for(int k = 0; k < 4; k++) {
          int x = w[j].x + dx[k], y = w[j].y + dy[k];
          if(x < 1 || y < 1 || x > n || y > n || v[cod(x, y)] < val)
            continue;
          join(tata(cod(w[j].x, w[j].y)), tata(cod(x, y)));
        }
        j++;
      }
      if(tata(cod(a[i].x1, a[i].y1)) == tata(cod(a[i].x2, a[i].y2)))
        a[i].ans += p;
    }
  }
  sort(a + 1, a + q + 1, comp);
  for(int i = 1; i <= q; i++)
    out << a[i].ans << "\n";
  return 0;
}