# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
970601 | dosts | Mecho (IOI09_mecho) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
#define sp << " " <<
#define int long long
#define vi vector<int>
#define pb push_back
#define F(xxx,yyy) for (int xxx=1;xxx<=yyy;xxx++)
#define pii pair<int,int>
#define ordered_set tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update>
void solve() {
int n,k;
cin >> n >> k;
char grid[n+1][n+1];
queue<pii> q;
vector<vi> bee(n+1,vi(n+1,-1));
int sx,sy,hx,hy;
F(i,n) {
string s;
cin >> s;
F(j,n) {
grid[i][j] = s[j-1];
if (s[j-1] == 'H') {
q.push({i,j});
bee[i][j] = 0;
}
if (s[j-1] == 'D') {
hx = i;
hy = j;
}
if (s[j-1] == 'M') {
sx = i;
sy = j;
}
}
}
vi dx = {1,0,-1,0};
vi dy = {0,1,0,-1};
while (!q.empty()) {
pii f = q.front();
q.pop();
int x = f.first;
int y = f.second;
for (int i=0;i<4;i++) {
int gx = x+dx[i];
int gy = y+dy[i];
if (gx < 1 || gx > n) continue;
if (gy < 1 || gy > n) continue;
if (grid[gx][gy] == 'T') continue;
if (grid[gx][gy] == 'D') continue;
if (bee[gx][gy] != -1) continue;
bee[gx][gy] = bee[x][y]+1;
q.push({gx,gy});
}
}
int l = 0;
int r = 1e9;
while (l<=r) {
int w = (l+r) >> 1;
if (w >= bee[sx][sy]) {
r = w-1;
continue;
}
vector<vi> dist(n+1,vi(n+1,-1));
dist[sx][sy] = 0;
q.push({sx,sy});
while (!q.empty()) {
pii f = q.front();
q.pop();
int x = f.first;
int y = f.second;
for (int i=0;i<4;i++) {
int gx = x+dx[i];
int gy = y+dy[i];
if (gx < 1 || gx > n) continue;
if (gy < 1 || gy > n) continue;
if (grid[gx][gy] == 'T') continue;
if (dist[gx][gy] != -1) continue;
if (bee[gx][gy] != -1 && bee[gx][gy] <= w+(d(ist[x][y]+k-1)/k)+1) continue;
dist[gx][gy] = dist[x][y]+1;
q.push({gx,gy});
}
}
if (dist[hx][hy]!=-1) l = w+1;
else r = w-1;
}
cout << r << endl;
}
signed main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t = 1;
//cin >> t;
while (t --> 0) solve();
}