Cod sursa(job #1585423)

Utilizator claudiuarseneClaudiu Arsene claudiuarsene Data 30 ianuarie 2016 23:47:08
Problema Barman Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.92 kb
#include <fstream>
#include  <queue>
using namespace std;
queue < pair < int, int> > q;
int n,m,i,w,j,z,t,o,p,x,y,k,b[1005][1005],d[1005][1005];
char c;
int main()
{
    ifstream f("barbar.in");
    ofstream g("barbar.out");
    int dx[]={-1,0,1,0};
    int dy[]={0,1,0,-1};
    f>>n>>m;
    for(i=1; i<=n; i++)
    for(j=1; j<=m; j++)
    {
        d[i][j]=1000005;
        b[i][j]=-1;
        f>>c;
        if(c=='*')
        {
            b[i][j]=1000005;
            d[i][j]=-1;
        }
        if(c=='D')
        {
            q.push(make_pair(i,j));
            d[i][j]=0;
        }
        if(c=='I')
        {
            z=i;
            t=j;
        }
        if(c=='O')
        {
            o=i;
            p=j;
        }
    }
    for(i=0; i<=n+1; i++)
    {
        b[i][0]=1000005;
        b[i][m+1]=1000005;
        d[i][0]=-1;
        d[i][m+1]=-1;
    }
    for(i=0; i<=m+1; i++)
    {
        b[0][i]=1000005;
        b[n+1][i]=1000005;
        d[0][i]=-1;
        d[n+1][i]=-1;
    }
    while(!q.empty())
    {
        i=q.front().first;
        j=q.front().second;
        q.pop();
        for(k=0; k<4; k++)
        {
            x=i+dx[k];
            y=j+dy[k];
            if(d[x][y]>d[i][j]+1)
            {
                d[x][y]=d[i][j]+1;
                q.push(make_pair(x,y));
            }
        }
    }
    q.push(make_pair(z,t));
    b[z][t]=d[z][t];
    while(!q.empty())
    {
        i=q.front().first;
        j=q.front().second;
        q.pop();
        for(k=0; k<4; k++)
        {
            x=i+dx[k];
            y=j+dy[k];
            w=b[i][j];
            if(d[x][y]<w) w=d[x][y];
            if(b[x][y]<w)
            {
                b[x][y]=w;
                q.push(make_pair(x,y));
            }
        }
    }
    if(b[o][p]>=0) g<<b[o][p]<<'\n';
    else g<<"-1\n";
    f.close(); g.close();
    return 0;
}