Cod sursa(job #2332320)

Utilizator AlexandruPaulSirbu Alex AlexandruPaul Data 30 ianuarie 2019 17:13:47
Problema Barbar Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.21 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define fi first
#define se second
using namespace std;
const int Maxx=1e3+1;
const int dx[]={-1,0,1,0};
const int dy[]={0,1,0,-1};
struct POINT{
    int x,y,cost;
    bool operator <(const POINT& a) const {
        return (this->cost)>a.cost;
    }
}nw,ac,str,stp;
priority_queue <POINT> Q;
queue < pair<int,int> > q;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m,i,j;
int dist[Maxx][Maxx];
int A[Maxx][Maxx];
char a;
bool test1(pair <int,int> f);
bool test(POINT a);
void lee();
int main() {
    fin>>n>>m;
    for (i=1;i<=n;++i){
        for (j=1;j<=m;++j){
            fin>>a;
            if (a=='I'){
                str.x=i;
                str.y=j;
            }
            if (a=='O'){
                stp.x=i;
                stp.y=j;
            }
            if (a=='*'){
                A[i][j]=-1;
            }
            if (a=='D'){
                A[i][j]=-1;
                q.push({i,j});
                dist[i][j]=1;
            }
        }
    }
    pair <int,int> f,g;
    int d;
    while (!q.empty()){
        f=q.front();
        q.pop();
        for (d=0;d<4;++d){
            g.fi=f.fi+dx[d];
            g.se=f.se+dy[d];
            if (test1(g) && dist[g.fi][g.se]==0){
                dist[g.fi][g.se]=dist[f.fi][f.se]+1;
                q.push(g);
            }
        }
    }
    lee();
    return 0;
}
bool test1(pair <int,int> f){
    return f.fi>0 && f.fi<=n && f.se>0 && f.se<=m;
}
bool test(POINT a){
    return a.x>0 && a.x<=n && a.y>0 && a.y<=m;
}
void lee(){
    str.cost=dist[str.x][str.y];
    Q.push(str);
    int d;
    while (!Q.empty()){
        ac=Q.top();
        Q.pop();
        if (A[ac.x][ac.y]!=0) continue;
        A[ac.x][ac.y]==1;
        if (ac.x==stp.x && ac.y==stp.y){
            fout<<min(ac.cost,dist[stp.x][stp.y]);
            return;
        }
        //fout<<ac.x<<" "<<ac.y<<"\n";
        for (d=0;d<4;++d){
            nw.x=ac.x+dx[d];
            nw.y=ac.y+dy[d];
            nw.cost=min(ac.cost,dist[nw.x][nw.y]);
            if (test(nw)){
                Q.push(nw);
            }
        }
    }
}