#include <bits/stdc++.h>
#include <cstdlib>
using namespace std;
using ll = long long;
using str = string;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pll = pair<ll, ll>;
using tiii = tuple<int, int, int>;
#define FOR(i, l, r) for (int i=l; i<=r; i++)
#define FOR2(i, l, r) for (int i=l; i>=r; i--)
#define ALL(v) v.begin(), v.end()
#define RALL(v) v.rbegin(), v.rend()
#define fi first
#define se second
#define ce cout << endl
#define pb push_back
#define pf push_front
#define pob pop_back
#define eb emplace_back
#define ep emplace
const ll MOD = 998244353;
const int INF = 1e9;
const int LOG = 60;
const double MAX = 1e9;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, 1, -1};
char direct[4] = {'U', 'D', 'R', 'L'};
// north, south, east, weast
void solve() {
int n, k; cin >> n >> k;
vector<str> forest(n);
pii mecho, home;
queue<pii> hive;
vector<vector<int>> dist_bee(n, vector<int> (n, -1));
FOR(i, 0, n-1) {
cin >> forest[i];
FOR(j, 0, n-1) {
if (forest[i][j] == 'M') mecho = {i, j};
else if (forest[i][j] == 'D') home = {i, j};
else if (forest[i][j] == 'H') {
hive.ep(i, j);
dist_bee[i][j] = 0;
}
}
}
function<bool(int x, int y)> inside = [&] (int x, int y) {
return x >= 0 && x < n && y >= 0 && y < n && forest[x][y] != 'T';
};
while (!hive.empty()) {
auto [x1, y1] = hive.front(); hive.pop();
// cout << x1 << ' ' << y1; ce;
FOR(i, 0, 3) {
int x2 = x1+dx[i], y2 = y1+dy[i];
if (!inside(x2, y2) || dist_bee[x2][y2] != -1) continue;
dist_bee[x2][y2] = dist_bee[x1][y1] + k;
hive.ep(x2, y2);
}
}
// FOR(i, 0, n-1) {
// FOR(j, 0, n-1) cout << dist_bee[i][j] << ' '; ce;
// }
function<bool(int minute)> bfs = [&] (int minute) {
if (minute*k > dist_bee[mecho.fi][mecho.se]) return false;
queue<pair<pii, int>> qe;
vector<vector<bool>> vis(n, vector<bool> (n, false));
qe.ep(mecho, minute*k);
vis[mecho.fi][mecho.se] = true;
while (!qe.empty()) {
auto [p, t] = qe.front(); qe.pop();
auto [x1, y1] = p;
if (pii{x1, y1} == home) return true;
FOR(i, 0, 3) {
int x2 = x1+dx[i], y2 = y1+dy[i];
if (!inside(x2, y2) || vis[x2][y2] || t+1 > dist_bee[x2][y2]) continue;
qe.ep(pii{x2, y2}, t+1);
vis[x2][y2] = true;
}
// cout << minute; ce;
// FOR(i, 0, n-1) {
// FOR(j, 0, n-1) cout << vis[i][j] << ' '; ce;
// } ce;
}
return false;
};
int low = -1, high = n*n;
while (low < high) {
int mid = (low + high + 1)/2;
if (bfs(mid)) low = mid;
else high = mid - 1;
}
cout << low;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
// freopen("atlarge.in", "r", stdin);
// freopen("atlarge.out", "w", stdout);
int t = 1;
// cin >> t;
while (t--) solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |