Submission #1355650

#TimeUsernameProblemLanguageResultExecution timeMemory
1355650lex._.Mecho (IOI09_mecho)C++20
84 / 100
165 ms8880 KiB
#include <bits/stdc++.h>
#define INF 1000000000
#define NMAX 800
#define x first
#define y second
using namespace std;

int n, s;
pair<int, int> start, home;

char m[NMAX+1][NMAX+1];
int dist_bees[NMAX+1][NMAX+1], dist_m[NMAX+1][NMAX+1];
int dif_min[NMAX+1][NMAX+1];

int dx[4]={0, -1, 0, 1};
int dy[4]={-1, 0, 1, 0};

bool valid(int x, int y)
{
    return (x>=1 && x<=n && y>=1 && y<=n);
}

bool possible(int minutes)
{
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
            dist_m[i][j]=INF;
    }
    dist_m[start.x][start.y]=minutes;
    queue<pair<int, int>> q;
    q.push(start);
    while(!q.empty())
    {
        auto [x, y]=q.front();
        q.pop();
        for(int d=0; d<4; d++)
        {
            int new_x=x+dx[d], new_y=y+dy[d];
            if(valid(new_x, new_y) && (m[new_x][new_y]=='G' || m[new_x][new_y]=='M' || m[new_x][new_y]=='D') && dist_m[new_x][new_y]==INF && dist_bees[new_x][new_y]>dist_m[x][y]+1)
            {
                dist_m[new_x][new_y]=dist_m[x][y]+1;
                q.push({new_x, new_y});
            }
        }
    }
    return (dist_m[home.x][home.y]!=INF);
}

int solve()
{
    int st=0, dr=INF, ans=-1;
    while(st<=dr)
    {
        int mij=st+(dr-st)/2;
        if(possible(mij))
        {
            ans=mij;
            st=mij+1;
        }
        else dr=mij-1;
    }
    if(ans!=-1) ans/=s;
    return ans;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n >> s;

    queue<pair<int, int>> q;
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
        {
            dist_bees[i][j]=dist_m[i][j]=INF;
            dif_min[i][j]=INF;

            cin >> m[i][j];
            if(m[i][j]=='H') {dist_bees[i][j]=0; q.push({i, j});}
            if(m[i][j]=='M') start={i, j};
            if(m[i][j]=='D') home={i, j};
        }
    }
    while(!q.empty())
    {
        auto [x, y]=q.front();
        q.pop();
        for(int d=0; d<4; d++)
        {
            int new_x=x+dx[d], new_y=y+dy[d];
            if(valid(new_x, new_y) && (m[new_x][new_y]=='G' || m[new_x][new_y]=='M') && dist_bees[new_x][new_y]==INF)
            {
                dist_bees[new_x][new_y]=dist_bees[x][y]+s;
                q.push({new_x, new_y});
            }
        }
    }

    cout << solve();

    return 0;
}
#Result Execution timeMemoryGrader output
Fetching results...