Cod sursa(job #2319053)

Utilizator AlexPascu007Pascu Ionut Alexandru AlexPascu007 Data 13 ianuarie 2019 20:02:15
Problema Barbar Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.02 kb
#include <fstream>
#include <cstring>
#include <queue>
#define DIM 1010
#define inf 2000000000
using namespace std;
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
int r,c,i,j,istart,jstart,istop,jstop,iv,jv,p,u,d[DIM][DIM],a[DIM][DIM];
int di[4] = {0, 0, 1, -1};
int dj[4] = {1, -1, 0 ,0};
char ch[DIM][DIM];
pair <int,int> v[DIM];
int main() {
    fin>>r>>c;
    for (i=1; i<=r; i++){
        for (j=1; j<=c; j++){
            fin>>ch[i][j];
            if (ch[i][j]=='D'){
                v[++u]={i,j};
                a[i][j]=0;
            }
            else {
                if (ch[i][j]=='I'){
                    istart=i;
                    jstart=j;
                }
                else if (ch[i][j]=='O'){
                    istop=i;
                    jstop=j;
                }
                a[i][j]=inf;
            }
        }
    }
    p=1;
    while (p<=u) {
        i=v[p].first;
        j=v[p].second;
        for (int dir=0; dir<4; dir++){
            iv=i+di[dir];
            jv=j+dj[dir];
            if (i >= 1 && i <= r && j >= 1 && j <= c && ch[i][j] != '*'&& a[iv][jv] > a[i][j] + 1){
                a[iv][jv]=a[i][j]+1;
                v[++u]={iv,jv};
            }
        }
        p++;
    }
    memset(d,-1,sizeof(d));
    v[1].first=istart, v[1].second=jstart;
    d[istart][jstart]=a[istart][jstart];
    p=u=1;
    while (p<=u){
        i=v[p].first;
        j=v[p].second;
        for (int dir=0; dir<4; dir++) {
            iv=i+di[dir];
            jv=j+dj[dir];
            if (i >= 1 && i <= r && j >= 1 && j <= c && ch[i][j] != '*'){
                if (d[iv][jv]==-1){
                    d[iv][jv]=min(a[iv][jv], d[i][j]);
                    v[++u]={iv,jv};
                }
                else if (d[iv][jv] < min(d[i][j], a[iv][jv])){
                    d[iv][jv]=min(d[i][j], a[iv][jv]);
                    v[++u]={iv,jv};
                }
            }
        }
        p++;
    }
    fout<<d[istop][jstop];
    return 0;
}