Cod sursa(job #2495877)

Utilizator AlexBolfaAlex Bolfa AlexBolfa Data 19 noiembrie 2019 22:20:49
Problema Matrice 2 Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.25 kb
#include <bits/stdc++.h>
#define NMAX 304
#define QMAX 20004
#define pb push_back
#define ft first
#define sd second
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
typedef pair <int, int> pairINT;
typedef long long ll;

int n,q,k,us[NMAX*NMAX],sz[NMAX*NMAX],sol[QMAX];
pair <int, pairINT> edge[NMAX*NMAX*5];
vector <int> g[NMAX*NMAX];
vector <pairINT> waiting[NMAX*NMAX];


void read();
void dfs(int,int,int,int);

int main(){
    read();
    for(int i=0,cost,x,y,u1,u2;i<k;++i){
        cost=edge[i].ft;
        x=edge[i].sd.ft, y=edge[i].sd.sd;

        u1=us[x], u2=us[y];

        if(u1!=u2){
            if(sz[u1] > sz[u2]){
                dfs(u1,y, u2,cost);
                sz[u1]+=sz[u2];
                sz[u2]=0;
            }else{
                dfs(u2, x, u1, cost);
                sz[u2]+=sz[u1];
                sz[u1]=0;
            }
        }
    }
    for(int i=0;i<q;++i)
        fout<<sol[i]<<'\n';
    return 0;
}
void dfs(int x,int y,int u,int cost){// union merge
    us[y]=x;
    for(auto it:waiting[y]){
        if(!sol[it.sd] && us[it.ft] == x)
            sol[it.sd]=cost;
    }
    for(auto it:g[y])
        if(us[it] == u)
            dfs(x, it, u, cost);
}

void read(){// & build graph
    int x,y,cost,m[NMAX][NMAX];
    fin>>n>>q;
    for(int i=1;i<=n;++i){
        for(int j=1;j<=n;++j){
            fin>>m[i][j];
            x=n*(i-1) + j;

            sz[x]=1;
            us[x]=x;

            if(i-1){
                y=n*(i-2) + j;
                cost=min(m[i][j], m[i-1][j]);
                edge[k++]={cost, {x, y}};
                edge[k++]={cost, {y, x}};
                g[x].pb(y);
                g[y].pb(x);
            }
            if(j-1){
                y=x-1;
                cost=min(m[i][j], m[i][j-1]);
                edge[k++]={cost, {y, x}};
                edge[k++]={cost, {x, y}};
                g[x].pb(y);
                g[y].pb(x);
            }
        }
    }
    sort(edge, edge+k, greater<pair <int, pairINT>>());
    for(int i=0,a,b;i<q;++i){
        fin>>a>>b;
        x=n*(a-1) + b;
        fin>>a>>b;
        y=n*(a-1) + b;

        waiting[x].pb({y, i});
        waiting[y].pb({x, i});
    }
}