Cod sursa(job #1108690)

Utilizator ion824Ion Ureche ion824 Data 15 februarie 2014 23:02:53
Problema Matrice 2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2 kb
#include<fstream>
#include<algorithm>
using namespace std;
const int dx[4]={0,1,-1,0};
const int dy[4]={1,0,0,-1};

struct E{ int x,y; }e[90003];
struct QR{ int ind,sx,sy,fx,fy,ans; } Q[20003];

int a[302][302],viz[302][302];
int GR[90003];

bool cmp1(const E &w, const E &ww){
     return (a[w.x][w.y] > a[ww.x][ww.y]);
     }
     
bool cmp2(const QR &a,const QR &b){
     return (a.ans > b.ans);
     }
     
bool cmp3(const QR &a,const QR &b){
     return (a.ind < b.ind);
     }     

int grupa(int k){
   if(GR[k]==k) return GR[k];
   GR[k]=grupa(GR[k]);
   return GR[k];   
}

int main(){
    ifstream cin("matrice2.in");
    ofstream cout("matrice2.out");
    int N,M,i,j,N2,pas;
    int L=0,step,g1,g2,x,y,t;

    cin>>N>>M; N2=N*N;
    for(i=1;i<=N;++i)
      for(j=1;j<=N;++j)
      {
        cin>>a[i][j];
        e[++L].x=i;
        e[L].y=j;
      }
    
    for(i=1;i<=M;++i){
      cin>>Q[i].sx>>Q[i].sy>>Q[i].fx>>Q[i].fy;
      Q[i].ind=i;   
      Q[i].ans=0;          
    }
    
    sort(e+1,e+L+1,cmp1);
    
    for(step=1; step < a[e[1].x][e[1].y]; step<<=1) ;
    pas=0;
    
    for(;step;step>>=1,pas++){
      for(i=1;i<=N2;++i) GR[i]=i;
      
      for(i=1,j=1;i<=M;++i){
         for(;j<=N2 && a[e[j].x][e[j].y] >= Q[i].ans + step;++j){
                    
           viz[e[j].x][e[j].y]=pas;                 
           
           for(t=0;t<4;++t){
             x=e[j].x + dx[t];
             y=e[j].y + dy[t];
             
             if(x>0 && y>0 && x<=N && y<=N && viz[x][y]==pas){
               g1=grupa((e[j].x-1)*N+e[j].y); g2=grupa((x-1)*N + y);
               if(g1!=g2) GR[g1]=g2;
             }                        
           }
         }
        if(grupa((Q[i].sx-1)*N+Q[i].sy)==grupa((Q[i].fx-1)*N+Q[i].fy))
          Q[i].ans+=step;             
      }
       sort(Q+1,Q+M+1,cmp2);                  
    }
   sort(Q+1,Q+M+1,cmp3);
    
   for(i=1;i<=M;++i)
     cout<<Q[i].ans<<'\n';
    
    
 return 0;   
}