Cod sursa(job #1382928)

Utilizator campionulFlavius Stoican campionul Data 9 martie 2015 19:06:03
Problema Barbar Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.45 kb
#include <iostream>
#include <fstream>
#include <queue>
#define nmax 1005
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m,p,a[nmax][nmax],g,v[nmax*nmax],dp[nmax][nmax],pa,pb,l,r;
char ch,st[nmax][nmax];
bool ok[nmax*nmax],f[nmax*nmax];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
queue<int>q,Q;
struct Coord{
 int x,y;
};
Coord s[nmax*nmax];
inline bool Valid(int i,int j){
 if(i < 1 || j < 1|| i > n || j > m)return false;
 return true;
}
inline void CREATE(){
 int b,x,y,t;
 while(!q.empty()){
    b=q.front();
    ok[b]=0;
    q.pop();
    for(int i=0;i<4;i++){
      x=s[b].x+dx[i];
      y=s[b].y+dy[i];
       if(Valid(x,y) && (!a[x][y] || a[x][y] > a[s[b].x][s[b].y]+1)){
         a[x][y]=a[s[b].x][s[b].y]+1;
         if(i==0)t=b+1;
         else if(i==1)t=b-1;
         else if(i==2)t=b-m;
         else if(i==3)t=b+m;
         if(!ok[t]){
            ok[t]=1;
            q.push(t);
         }
       }
    }
 }
 for(int i=1;i<=n;i++)
    for(int j=1;j<=m;j++)
     r=max(r,a[i][j]);
// for(int i=1;i<=n;i++){
//    for(int j=1;j<=m;j++)
//        fout<<a[i][j]<<' ';
//    fout<<'\n';
// }

}
inline bool BFS(int lg){
 int i,j,b,x,y,sa,sb;
 for(i=1;i<=n;i++)
    for(j=1;j<=m;j++)
     if(dp[i][j]!=-1)dp[i][j]=-2;
 Q.push(g);
 f[g]=1;
 dp[s[g].x][s[g].y]=0;
  while(!Q.empty()){
     b=Q.front();
     f[b]=0;
     Q.pop();
     sa=s[b].x;sb=s[b].y;
     for(i=0;i<4;i++){
      x=sa+dx[i];
      y=sb+dy[i];
      g=m*(x-1)+y;
      if(Valid(x,y)&& (dp[x][y] > dp[sa][sb]+1||dp[x][y]==-2)&&st[x][y]!='*'&&st[x][y]!='D'&&a[x][y] >= lg){
        dp[x][y]=dp[sa][sb]+1;
        if(!f[g]){
            Q.push(g);
            f[g]=1;
        }
      }
     }
  }
//   for(int i=1;i<=n;i++){
//    for(int j=1;j<=m;j++)
//        fout<<dp[i][j]<<"  ";
//    fout<<'\n';
// }
 if(dp[pa][pb]>0)
    return 1;
 return 0;
}
int main(){
    int i,j,mij,x;
    fin >> n >> m;
    for(i=1;i<=n;i++)
        for(j=1;j<=m;j++)
         {fin>>st[i][j];
          if(st[i][j]=='I')g=p+1;
         else if(st[i][j]=='*')dp[i][j]=-1;
         s[++p].x=i;s[p].y=j;
         if(st[i][j]=='D') {q.push(p);ok[p]=1;}
         if(st[i][j]=='O'){pa=i;pb=j;}
        }
    fin.close();
    CREATE();
    j=-1;
    l=1;
    while(l<=r){
     mij=(l+r)/2;
      x=BFS(mij);
      if(!x)r=mij-1;
      else {j=mij;l=mij+1;}
    }
    fout<<j;
    fout.close();
    return 0;
}