Cod sursa(job #2319097)

Utilizator AlexPascu007Pascu Ionut Alexandru AlexPascu007 Data 13 ianuarie 2019 20:22:04
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <fstream>
#include <cstring>
#include <queue>
#define DIM 1001
using namespace std;
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
const int inf=2000000000;
int d[DIM][DIM], a[DIM][DIM];
int r,c,i,j,istart,jstart,istop,jstop,iv,jv;
int di[4] = {0, 0, 1, -1};
int dj[4] = {1, -1, 0 ,0};
char ch[DIM][DIM];
inline bool valid(int i,int j) {
	return(i >= 1 && i <= r && j >= 1 && j <= c && ch[i][j] != '*');
}
queue <int> q1,q2;
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'){
                q1.push(i);
                q2.push(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;
            }
        }
    }
    while (!q1.empty()){
        i=q1.front();
        j=q2.front();
        q1.pop();
        q2.pop();
        for (int dir=0; dir<4; dir++){
            iv=i+di[dir];
            jv=j+dj[dir];
            if (valid(iv,jv)&& a[iv][jv] > a[i][j] + 1){
                a[iv][jv]=a[i][j]+1;
                q1.push(iv);
                q2.push(jv);
            }
        }
    }
    memset(d,-1,sizeof(d));
    q1.push(istart);
	q2.push(jstart);
    d[istart][jstart]=a[istart][jstart];
    while (!q1.empty()) {
        i=q1.front();
        j=q2.front();
        q1.pop();
        q2.pop();
        for (int dir=0; dir<4; dir++) {
            iv=i+di[dir];
            jv=j+dj[dir];
            if (valid(iv,jv)){
                if (d[iv][jv]==-1){
                    d[iv][jv]=min(a[iv][jv], d[i][j]);
                    q1.push(iv);
					q2.push(jv);
                }
                else if (d[iv][jv] < min(d[i][j], a[iv][jv])){
                    d[iv][jv]=min(d[i][j], a[iv][jv]);
                    q1.push(iv);
					q2.push(jv);
                }
            }
        }
    }
    fout<<d[istop][jstop];
    return 0;
}