Cod sursa(job #2319008)

Utilizator AlexPascu007Pascu Ionut Alexandru AlexPascu007 Data 13 ianuarie 2019 19:46:19
Problema Barbar Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.66 kb
#include <fstream>
#include <cstring>
#define DIM 1010
#define inf 2000000000
#define x first
#define y second
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int r,c,i,j,a[DIM][DIM],istart,jstart,istop,jstop,iv,jv,k,st,dr,mid,d[DIM][DIM],ok,p,u;
int di[]={-1,1,0,0};
int dj[]={0,0,-1,1};
pair<int,int> v[DIM];
char ch[DIM][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]=='I') {
				istart=i;
				jstart=j;
			}
			if (ch[i][j]=='O') {
				istop=i;
				jstop=j;
			}
			if (ch[i][j]=='D') {
				a[i][j]=0;
				u++;
				v[u].x=i; v[u].y=j;
				continue;
			}
			a[i][j]=inf;
		}
	p=1;
    while (p<=u) {
        for (int dir=0;dir<=3;dir++) {
            iv=v[p].x+di[dir];
            jv=v[p].y+dj[dir];
            if (iv>=1&&iv<=r&jv>=1&&jv<=c&&ch[iv][jv]!='*'&&a[iv][jv]>a[v[p].x][v[p].y]+1) {
                u++;
                v[u].x=iv;
                v[u].y=jv;
                a[iv][jv]=1+a[v[p].x][v[p].y];
            }
        }
        p++;
    }
    for (i=1;i<=r;i++)
		for (j=1;j<=c;j++)
			d[i][j]=-1;
	d[istart][jstart]=a[istart][jstart];
	p=u=1;
	v[1].x=istart, v[1].y=jstart;
	while (p<=u) {
		i=v[p].x, j=v[p].y;
		for (int dir=0;dir<4;dir++) {
			iv=i+di[dir];
			jv=j+dj[dir];
			if (iv>=1&&iv<=r&&jv>=1&&jv<=c) {
				if (d[iv][jv]==-1) {
					d[iv][jv]=min(a[iv][jv],d[i][j]);
					u++;
					v[u].x=iv, v[u].y=jv;
				}
				else if (d[iv][jv]<min(a[iv][jv],d[i][j])) {
					d[iv][jv]=min(a[iv][jv],d[i][j]);
					u++;
					v[u].x=iv, v[u].y=jv;
				}
			}
		}
		p++;
	}
	fout<<d[istop][jstop];
	return 0;
}