Cod sursa(job #1232848)

Utilizator buzu.tudor67Tudor Buzu buzu.tudor67 Data 24 septembrie 2014 00:38:29
Problema Matrice 2 Scor 35
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.4 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];
int lastx[max_n*max_n],lasty[max_n*max_n],k;

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 i=1;i<=k;i++) viz[lastx[i]][lasty[i]]=0;
     k=0;
                          
     q.push(make_pair(x1,y1));
     viz[x1][y1]=1; 
     lastx[++k]=x1;
     lasty[k]=y1;
     
     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[xn][yn] && a[xn][yn]>=h)
                 {
                  q.push(make_pair(xn,yn));
                  viz[xn][yn]=1; 
                  lastx[++k]=xn;
                  lasty[k]=yn;
                  if(xn==x2 && yn==y2){
                                       while(q.size()) q.pop(); 
                                       return 1; 
                                      }
                 }
              }
           
           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;
                     }
        
        fo<<sol<<"\n";
       }
    
    fi.close();
    fo.close();
    return 0;
}