Cod sursa(job #1066069)

Utilizator blasterzMircea Dima blasterz Data 23 decembrie 2013 23:43:54
Problema Matrice 2 Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.05 kb
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
 
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
 
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
 
#define NMAX 90004
#define lim (1 << 20)
 
int xs, ys, xf, yf;
int i, j, k, N, Q;
int n, cnt;
int cmax;
 
int t[NMAX];
int Cost[NMAX];
int P[NMAX];
int X[NMAX], Y[NMAX];
int a[301][301];
 
int l, ll;
int c, cc;
 
struct cmp {
    bool operator()(const int &a, const int &b)const {
        if (Cost[a] > Cost[b]) return 1;
        return 0;
    };
};
 
inline int isOk(int x, int y){if (x >= 1 && x <= N && y >= 1 && y <= N) return 1; return 0;}
 
inline int Find(int x) {
    if (x != t[x]) t[x] = Find(t[x]);
    return t[x];
}
 
inline int isRoad(int C) {
    int j;
    if (C > min(Cost[a[xs][ys]], Cost[a[xf][yf]])) return 0;
    for (j = 1; j <= n; ++j) t[j] = j;
    for (j = 1; j <= n; ++j) {
        if (Cost[P[j]] < C) {
            if (Find(a[xs][ys]) != Find(a[xf][yf]))
                return 0;
            return 1;
        }
        l = X[P[j]];
        c = Y[P[j]];
        for (int k = 0; k < 4; ++k) {
            ll = l + dx[k];
            cc = c + dy[k];
            if (isOk(ll, cc) && Cost[a[ll][cc]] >= C) {
                int Father2 = Find(a[ll][cc]);
                int Father1 = Find(a[l][c]);
                t[Father1] = Father2;
            }
        }
    }
    if (Find(a[xs][ys]) != Find(a[xf][yf]))
        return 0;
    return 1;
}
 
inline int Binary_Search() {
    int cnt, i;
    for (i = 0, cnt = lim; cnt; cnt >>= 1)
        if (i + cnt <= cmax && isRoad(i + cnt)) 
            i += cnt;
    return i;
}
 
int main() {
    fin >> N >> Q;
    for (i = 1; i <= N; ++i) {
        for (j = 1; j <= N; ++j) {
            ++n;
            fin >> Cost[n];
            cmax = max(cmax, Cost[n]);
            X[n] = i; Y[n] = j;
            a[i][j] = n;
            P[n] = n;
        }
    }
    sort(P + 1, P + n + 1, cmp());
    for (j = 1; j <= Q; ++j) {
        fin >> xs >> ys >> xf >> yf;
        fout << Binary_Search() << '\n';
    }
    return 0;
}