Cod sursa(job #2637737)

Utilizator OvidRata Ovidiu Ovid Data 24 iulie 2020 16:38:22
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.27 kb
#include<bits/stdc++.h>
using namespace std;
#define INIT  ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define mp make_pair
#define pb push_back
#define ft first
#define sc second
#define ll long long
#define pii pair<int, int>
#define count_bits __builtin_popcount
#define int ll

int r, c;
char m[1010][1010];
int d[1010][1010];
ifstream fin("barbar.in"); ofstream fout("barbar.out");
#define cin fin
#define cout fout
queue<pii> drag;
bool v[1010][1010];


void dist(){
vector<int> Y={1, -1, 0, 0};
vector<int> X={0,  0, 1, -1};
while(!drag.empty()){
    pii f=drag.front(); drag.pop();
    for(int g=0; g<4; g++){
        int y=min(max((int)1, f.ft+Y[g]), r), x=min(max((int)1, f.sc+X[g]), c);
        if( (!v[y][x]) && (m[y][x]!='*') ){
            v[y][x]=true;
            d[y][x]=d[f.ft][f.sc]+1;
            drag.push(mp(y, x));
        }
    }


}
return ;
}




pii paf, lst;
void bfs(int dist){
for(int i=1; i<=r; i++){
    for(int j=1; j<=c; j++){
        v[i][j]=false;
    }
}
v[paf.ft][paf.sc]=true;
queue<pii> q; q.push(paf);
vector<int> Y={1, -1, 0, 0};
vector<int> X={0,  0, 1, -1};
if(d[paf.ft][paf.sc]<dist){return;}
while(!q.empty()){
    pii f=q.front(); q.pop();
    for(int g=0; g<4; g++){
         int y=min(max((int)1, f.ft+Y[g]), r), x=min(max((int)1, f.sc+X[g]), c);
         if( (!v[y][x]) && (d[y][x]>=dist) && (m[y][x]!='*') ){
            v[y][x]=true;
            q.push(mp(y, x));
            if(m[y][x]=='O'){ return;}
         }
    }
}
return;

}










int32_t main(){
INIT
fin>>r>>c;
for(int i=1; i<=r; i++){
    for(int j=1; j<=c; j++){
        cin>>m[i][j];
        if(m[i][j]=='D'){
            drag.push(mp(i, j));
            v[i][j]=true;
        }
        if(m[i][j]=='I'){
            paf=mp(i, j);
        }
        if(m[i][j]=='O'){
            lst=mp(i, j);
        }
    }
}
dist();



int L=0, R=2000, M;


while(L<R){
    M=(L+R)/2;
    bfs(2000-M);
    if(v[lst.ft][lst.sc]==true){
        R=M;
    }
    else{
        L=M+1;
    }
    M=(L+R)/2;
}
bfs(2000-M);
if(!v[lst.ft][lst.sc]){cout<<-1; return 0;}

cout<<(2000-M);







return 0;
}