제출 #816005

#제출 시각아이디문제언어결과실행 시간메모리
816005powervic08Mecho (IOI09_mecho)C++17
100 / 100
161 ms6524 KiB
#include <iostream>
#include <vector>
#include <queue>
#define pii pair<int, int>
 
using namespace std;
 
int N, S;
int mR, mC, dR, dC;
char grid[801][801];
int minHiveDist[801][801], minBearDist[801][801];
 
const int dx[4] = { -1, 1, 0, 0 };
const int dy[4] = { 0, 0, -1, 1 };
bool isValid(int r, int c) { return 0 <= r && r < N && 0 <= c && c < N; }
 
vector<vector<bool>> visited;
void bfs(vector<pii> initialCoords) {
	queue<pair<pii, int>> q; 
	visited.clear(); visited.resize(N, vector<bool>(N));
	for (pii p : initialCoords) {
		q.push({ p, 0 }); visited[p.first][p.second] = true;
	}
	while (!q.empty()) {
		pii loc = q.front().first; int dist = q.front().second; q.pop();
		minHiveDist[loc.first][loc.second] = dist;
		for (int i = 0; i < 4; i++) {
			int r = loc.first + dx[i], c = loc.second + dy[i];
			if (isValid(r, c) && !visited[r][c] && grid[r][c] != 'T' && grid[r][c] != 'D') {
				visited[r][c] = true;
				q.push({ {r, c}, dist + S });
			}
		}
	}
}
 
void bfs2(int startR, int startC, int wait) {
	visited.clear(); visited.resize(N, vector<bool>(N));
	if (minHiveDist[startR][startC] <= wait * S) return;
	queue<pair<pii, int>> q; q.push({ {startR, startC}, wait * S });
	visited[startR][startC] = true;
	while (!q.empty()) {
		pii loc = q.front().first; int dist = q.front().second; q.pop();
		minBearDist[loc.first][loc.second] = dist;
		for (int i = 0; i < 4; i++) {
			int r = loc.first + dx[i], c = loc.second + dy[i];
			if (isValid(r, c) && !visited[r][c] && grid[r][c] != 'T') {
				if (dist + 1 < minHiveDist[r][c]) {
					visited[r][c] = true;
					q.push({ {r, c}, dist + 1 });
				}
			}
		}
	}
}
bool works(int wait) {
	bfs2(mR, mC, wait);
	return visited[dR][dC];
}
 
int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
 
	cin >> N >> S;
	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++)
			cin >> grid[i][j];
	
	vector<pii> hives;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) {
			if (grid[i][j] == 'H') hives.push_back({ i, j });
			if (grid[i][j] == 'M') { mR = i; mC = j; }
			if (grid[i][j] == 'D') { dR = i; dC = j; }
		}
	}
 
	bfs(hives); minHiveDist[dR][dC] = (int)1e9;
 
	int low = 0, high = N * N;
	while (low < high) {
		int mid = (low + high + 1) / 2;
		if (works(mid)) low = mid;
		else high = mid - 1;
	} cout << (works(low) ? low : low - 1) << endl;
}
#Verdict Execution timeMemoryGrader output
Fetching results...