Cod sursa(job #3297704)

Utilizator eric.mesterEric Mestereaga eric.mester Data 23 mai 2025 15:43:45
Problema Barbar Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.88 kb
#include <bits/stdc++.h>
#define NMAX 1002

using namespace std;

ifstream fin("barbar.in");
ofstream fout("barbar.out");

struct pos{
    int y,x,d;
};

bool operator<(const pos &p1, const pos&p2)
{
    return p1.d < p2.d;
}

int N,M;
int stx,sty,fix,fiy;
char a[NMAX][NMAX];
priority_queue <pos> pq;
queue <pos> q;
int ans[NMAX][NMAX];
int dist[NMAX][NMAX];

bool isin(int y,int x)
{
    return y>=1 && x>=1 && y<=N && x<=M;
}

int main()
{
    fin >> N >> M;
    for(int i=1;i<=N;i++){
        for(int j=1;j<=M;j++){
            fin >> a[i][j];
            if(a[i][j]=='D'){
                q.push({i,j,1});
                a[i][j]='.';
            }else if(a[i][j]=='I'){
                stx=j;
                sty=i;
                a[i][j]='.';
            }else if(a[i][j]=='O'){
                fix=j;
                fiy=i;
                a[i][j]='.';
            }
        }
    }
    ///gasim dist pana la dragoni
    while(!q.empty()){
        int y=q.front().y;
        int x=q.front().x;
        int d=q.front().d;
        q.pop();
        if(isin(y,x) && a[y][x]=='.' && dist[y][x]==0){
            dist[y][x]=d;
            d++;
            q.push({y+1,x,d});
            q.push({y-1,x,d});
            q.push({y,x+1,d});
            q.push({y,x-1,d});
        }
    }
    for(int i=1;i<=N;i++){
        for(int j=1;j<=M;j++){
            dist[i][j]--;
//            cout << dist[i][j] << " ";
        }
//        cout << "\n";
    }
    ///acuma gasim drumu bun
    pq.push({sty,stx,dist[sty][stx]});
    while(!pq.empty()){
        int y=pq.top().y;
        int x=pq.top().x;
        int d=pq.top().d;
        pq.pop();
        if(isin(y,x) && a[y][x]=='.' && ans[y][x]==0){
            d=min(d,dist[y][x]);
            ans[y][x]=d;
            pq.push({y+1,x,d});
            pq.push({y-1,x,d});
            pq.push({y,x+1,d});
            pq.push({y,x-1,d});
        }
    }
    fout << ans[fiy][fix];
}