Cod sursa(job #1992121)

Utilizator DjokValeriu Motroi Djok Data 19 iunie 2017 15:35:52
Problema Matrice 2 Scor 100
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 1.96 kb
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;

const int N = 305;
const int Q = 20005;
const int BIN = 1000005;
const int dx[] = {0, 0, -1, 1};
const int dy[] = {-1, 1, 0, 0};

int i, j, dir, n, q, a[N][N], p[N * N], st[Q], dr[Q];
short x[Q], y[Q], xx[Q], yy[Q];
vector<unsigned short> pivot[BIN];
vector<pair<short, short>> e;

int pfind(int x) { return p[x] == x ? x : p[x] = pfind(p[x]); }

void punite(int x, int y) { p[pfind(x)] = pfind(y); }

int main() {
  ifstream cin("matrice2.in");
  ofstream cout("matrice2.out");
  ios_base::sync_with_stdio(0);

  e.reserve(n * n);
  cin >> n >> q;
  for(i = 1; i <= n; ++i)
    for(j = 1; j <= n; ++j) {
      cin >> a[i][j];
      e.push_back(make_pair(i, j));
    }

  sort(e.begin(), e.end(), [](pair<int, int> x, pair<int, int> y) {
    return a[x.x][x.y] > a[y.x][y.y];
  });

  for(i = 1; i <= q; ++i) {
    cin >> x[i] >> y[i] >> xx[i] >> yy[i];
    st[i] = 1; dr[i] = BIN;
  }

  while(1) {
    bool stopIt = 1;

    for(i = 1; i < BIN; ++i) pivot[i].clear();

    for(i = 1; i <= q; ++i) {
      if(st[i] > dr[i]) continue;
      stopIt = 0;
      pivot[(st[i] + dr[i]) / 2].push_back(i);
    }

    if(stopIt) break;

    for(i = j = 0; i <= n * n; ++i) p[i] = i;

    for(i = BIN - 1; i > 0; --i) {
      while(j < e.size() && a[e[j].x][e[j].y] >= i) {
        for(dir = 0; dir < 4; ++dir) {
          int newx = e[j].x + dx[dir];
          int newy = e[j].y + dy[dir];
          if(newx <= 0 || newy <= 0) continue;
          if(newy > n || newx > n) continue;
          if(a[newx][newy] < i) continue;
          punite((e[j].x - 1) * n + e[j].y, (newx - 1) * n + newy);
        }
        ++j;
      }

      for(auto it : pivot[i])
        if(pfind((x[it] - 1) * n + y[it]) == pfind((xx[it] - 1) * n + yy[it])) st[it] = i + 1;
        else dr[it] = i - 1;
    }
  }

  for(i = 1; i <= q; ++i) cout << dr[i] << '\n';

  return 0;
}