Cod sursa(job #1232845)

Utilizator buzu.tudor67Tudor Buzu buzu.tudor67 Data 24 septembrie 2014 00:26:25
Problema Matrice 2 Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.06 kb
#include<fstream>
#include<queue>
using namespace std;
ifstream fi("matrice2.in");
ofstream fo("matrice2.out");

const int max_n = 302;
const int dx[]={0,0,-1,1};
const int dy[]={1,-1,0,0};

queue < pair<int,int> > q;
int i,j,n,a[max_n][max_n];
int Q,x1,y1,x2,y2;
int st,dr,mijl,hmax;
bool viz[max_n*max_n];

bool este(const int &x, const int &y){ return (x>=1 && x<=n && y>=1 && y<=n); }

bool BFS(const int &x1, const int &y1, const int &x2, const int &y2, const int &h){
     
     for(int j=1;j<=n*n;j++) viz[j]=0;
     
     q.push(make_pair(x1,y1));
     viz[(n-1)*x1+y1]=1;
     
     if(a[x1][y1]<h){
                     while(q.size()) q.pop(); 
                     return 0;
                    }
     
     while(q.size())
          {
           int x=q.front().first;
           int y=q.front().second;
           
           if(x==x2 && y==y2){
                              while(q.size()) q.pop(); 
                              return 1; 
                             }
           
           for(int j=0;j<4;j++)
              {
               int xn=x+dx[j];
               int yn=y+dy[j];
               
               if(este(xn,yn) && !viz[(n-1)*xn+yn] && a[xn][yn]>=h)
                 {
                  q.push(make_pair(xn,yn));
                  viz[(n-1)*xn+yn]=1; 
                 }
              }
           
           viz[(n-1)*x+y]=0;   
           q.pop();
          }
     
     return 0;
}

int main(){
    fi>>n>>Q;
    
    for(i=1;i<=n;i++)
      for(j=1;j<=n;j++){
                        fi>>a[i][j];
                        if(a[i][j]>hmax) hmax=a[i][j];
                       }
    
    for(;Q;--Q)
       {
        fi>>x1>>y1>>x2>>y2;
        
        int sol=0;
        st=1; dr=hmax;
        while(st<=dr){
                      mijl=(st+dr)>>1;
                      if(BFS(x1,y1,x2,y2,mijl)){ sol=mijl; st=mijl+1; }
                      else dr=mijl-1;
                     }
        
        fo<<sol<<"\n";
       }
    
    fi.close();
    fo.close();
    return 0;
}