Cod sursa(job #2495370)

Utilizator AlexBolfaAlex Bolfa AlexBolfa Data 19 noiembrie 2019 11:42:14
Problema Matrice 2 Scor 35
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.26 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,urm[NMAX*NMAX], sz[NMAX*NMAX], sol[QMAX],k;
bool usedq[NMAX*NMAX];
pair <int, pairINT> edge[NMAX*NMAX*5];
vector <pairINT> waiting[NMAX*NMAX];


void read();
void umerge(int,int,int);
int getu(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=getu(x), u2=getu(y);
        if(u1!=u2){
            if(sz[u1] > sz[u2])
                umerge(u1,u2,cost);
            else
                umerge(u2, u1, cost);
        }
    }
    for(int i=0;i<q;++i)
        fout<<sol[i]<<'\n';
    return 0;
}
void umerge(int x,int y,int cost){// merge x with y
    int u;
    while(!waiting[y].empty()){
        u=getu(waiting[y].back().ft);
        if(u == x && !usedq[waiting[y].back().sd]){

            sol[waiting[y].back().sd]=cost;
            usedq[waiting[y].back().sd]=1;

        }else if(!usedq[waiting[y].back().sd])
            waiting[x].pb(waiting[y].back());

        waiting[y].pop_back();
    }
    urm[y]=x;
    sz[y]+=sz[x];
}
int getu(int node){
    while(urm[node]) node=urm[node];
    return node;
}
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;

            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}};
            }
            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}};
            }
        }
    }
    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});
    }
}