Cod sursa(job #2451240)

Utilizator stefanpiturStefan Alexandru Pitur stefanpitur Data 26 august 2019 11:43:58
Problema Barbar Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.71 kb
#include <iostream>
#include <cstdio>
#include <queue>
#define BIG 1000000
#define NMAX 1002
using namespace std;
int harta[NMAX][NMAX];
bool visited[NMAX][NMAX];
queue <pair<int, int> > dragoni;
pair<int, int> start, stop;
int dl[] = {-1, 0, 1, 0};
int dc[] = {0, 1, 0, -1};

bool bfs(int limit){
    int x,y,new_x,new_y,dir;
    queue <pair<int, int> > path;
    path.push(start);
    while(!path.empty()){
        x = path.front().first;
        y = path.front().second;
        path.pop();
        visited[x][y] = true;
        if(x == stop.first && y == stop.second)
            return true;
        for(dir = 0;dir<4;dir++){
            new_x = x + dl[dir];
            new_y = y + dc[dir];
            if(harta[new_x][new_y] != -1 && !visited[new_x][new_y] && harta[new_x][new_y] >= limit)
                path.push(make_pair(new_x,new_y));
        }
    }
    return false;
}

void clean(int r, int c){
    for(int i=1;i<=r;i++)
        for(int j=1;j<=c;j++)
            visited[i][j] = false;
}

int main()
{
    FILE *fin, *fout;
    int r,c,x,y,new_x,new_y,i,j,dir,li,ls,mij;
    char e;
    bool success;
    fin = fopen("barbar.in","r");
    fout = fopen("barbar.out","w");
    fscanf(fin,"%d %d\n",&r,&c);
    for(i=0;i<=r+1;i++)
        harta[i][0] = harta[i][c+1] = -1;
    for(j=0;j<=c+1;j++)
        harta[0][j] = harta[r+1][j] = -1;
    for(i=1;i<=r;i++){
        for(j=1;j<=c;j++){
            e = fgetc(fin);
            if(e == '*')
                harta[i][j] = -1;
            else if(e == 'D'){
                visited[i][j] = true;
                dragoni.push(make_pair(i,j));
            }
            else if(e == 'I')
                start = make_pair(i,j);
            else if(e == 'O')
                stop = make_pair(i,j);
            else
                harta[i][j] = 0;
        }
        fgetc(fin);
    }
    while(!dragoni.empty()){
        x = dragoni.front().first;
        y = dragoni.front().second;
        visited[x][y] = true;
        dragoni.pop();
        for(dir=0;dir<4;dir++){
            new_x = x + dl[dir];
            new_y = y + dc[dir];
            if(!visited[new_x][new_y] && harta[new_x][new_y] != -1){
                harta[new_x][new_y] = harta[x][y] + 1;
                dragoni.push(make_pair(new_x, new_y));
            }
        }
    }
    li = 0, ls = min(harta[start.first][start.second], harta[stop.first][stop.second]);
    while(li <= ls){
        mij = (li + ls) / 2;
        clean(r,c);
        success = bfs(mij);
        if(success == true)
            li = mij + 1;
        else
            ls = mij - 1;
    }
    fprintf(fout,"%d\n",li - 1);
    fclose(fin);
    fclose(fout);
    return 0;
}