Cod sursa(job #2112066)

Utilizator patcasrarespatcas rares danut patcasrares Data 22 ianuarie 2018 22:29:55
Problema Matrice 2 Scor 15
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.87 kb
#include<fstream>
#include<algorithm>
#include<cstring>
#include<vector>
#define DN 305
#define DQ 20005
#define DM 1000005
#define pb push_back
#define x1 first.first
#define y1 first.second
#define x2 second.first
#define y2 second.second
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
int n,m,q,a[DN][DN],pr[DN*DN],ma,lnou,cnou,p1,p2,nr,r[DQ],b[DN][DN];
typedef pair<int,int> pii;
pair<pii,pii>v[DQ];
vector<pii>l[DM];
int dl[4]={1,-1,0,0};
int dc[4]={0,0,1,-1};
int inside(int l,int c)
{
    if(l>=1&&l<=n&&c>=1&&c<=n)
        return 1;
    return 0;
}
int getpr(int a)
{
    if(a==pr[a])
        return a;
    pr[a]=getpr(pr[a]);
    return pr[a];
}
void reuniune(int l1,int c1,int l2,int c2)
{
    p1=getpr(b[l1][c1]);
    p2=getpr(b[l2][c2]);
    if(p1!=p2)
        pr[p1]=p2;
}
int main()
{
    fin>>n>>q;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        {
            fin>>a[i][j];
            nr++;
            b[i][j]=nr;
            pr[nr]=nr;
            l[a[i][j]].pb({i,j});
            ma=max(ma,a[i][j]);
        }
    for(int i=1;i<=q;i++)
        fin>>v[i].x1>>v[i].y1>>v[i].x2>>v[i].y2;
    for(int h=ma;h>=1;h--)
    {
        for(auto t:l[h])
        {
            int i=t.first;
            int j=t.second;
            for(int d=0;d<4;d++)
            {
                lnou=i+dl[d];
                cnou=j+dc[d];
                if(inside(lnou,cnou))
                    if(a[lnou][cnou]>=h)
                        reuniune(lnou,cnou,i,j);
            }
        }
        for(int i=1;i<=q;i++)
            if(r[i]==0)
            {
                p1=getpr(b[v[i].x1][v[i].y1]);
                p2=getpr(b[v[i].x2][v[i].y2]);
                if(p1==p2)
                    r[i]=h;
            }
    }
    for(int i=1;i<=q;i++)
        fout<<r[i]<<'\n';
}