Cod sursa(job #1769185)

Utilizator alexpetrescuAlexandru Petrescu alexpetrescu Data 2 octombrie 2016 00:19:39
Problema Matrice 2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.03 kb
#include <cstdio>
#include <utility>
#include <algorithm>

#define x first
#define y second
#define mycreation std::pair <int, int>

#define MAXN 300
#define MAXQ 20000
#define MAXK (MAXN+2)*(MAXN+2)

#define NRDIR 4
int dl[NRDIR]={-1, 0, 1, 0};
int dc[NRDIR]={0, 1, 0, -1};

struct godscreation{
    int x, y, z;
}r[MAXQ];

mycreation v[MAXK];
int poz[MAXK], ans[MAXQ];
int t[MAXK];

bool cmp1(const mycreation a, const mycreation b){
    return a.x>b.x;
}

bool cmp2(const godscreation a, const godscreation b){
    return ans[a.z]>ans[b.z];
}

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

int main(){
    int n, q, k, x, y, z, e, p, u;
    FILE *fin, *fout;
    fin=fopen("matrice2.in", "r");
    fout=fopen("matrice2.out", "w");
    fscanf(fin, "%d%d", &n, &q);
    k=0;
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++){
            fscanf(fin, "%d", &x);
            k++;
            v[k].x=x;
            v[k].y=i*(n+1)+j;
        }
    }
    std::sort(v+1, v+k+1, cmp1);
    for(int i=1; i<=k; i++)
        poz[v[i].y]=i;
    for(int i=0; i<q; i++){
        fscanf(fin, "%d%d%d%d", &x, &y, &z, &e);
        r[i].x=poz[x*(n+1)+y];
        r[i].y=poz[z*(n+1)+e];
        r[i].z=i;
        ans[i]=0;
    }
    for(int pas=1<<19; pas; pas>>=1){
        std::sort(r, r+q, cmp2);
        for(int i=1; i<=k; i++)
            t[i]=i;
        p=0;
        for(int i=1; i<=k; i++){
            while((p<q)&&(ans[r[p].z]+pas>v[i].x)){
                ans[r[p].z]+=pas*(find(r[p].x)==find(r[p].y));
                p++;
            }
            for(int j=0; j<NRDIR; j++){
                u=poz[v[i].y+dl[j]*(n+1)+dc[j]];
                if((u>0)&&(u<i)) t[find(i)]=find(u);
            }
        }
        while((p<q)&&(ans[r[p].z]+pas>0)){
            ans[r[p].z]+=pas*(find(r[p].x)==find(r[p].y));
            p++;
        }
    }
    for(int i=0; i<q; i++)
        fprintf(fout, "%d\n", ans[i]);
    fclose(fin);
    fclose(fout);
    return 0;
}