Submission #153031

#TimeUsernameProblemLanguageResultExecution timeMemory
153031tselmegkhMecho (IOI09_mecho)C++14
43 / 100
271 ms4572 KiB
#include<bits/stdc++.h>
using namespace std;

const int N = 805, inf = 1e9;
string a[N];
int d[N][N], dis[N][N], n, s;
bool vis[N][N];
pair<int, int> st, en;
int mx = 0;
int movex[] = {1, 0, -1, 0};
int movey[] = {0, 1, 0, -1};
vector<pair<int, int>> allhives;

void fill(){
	for(int i = 0; i < 801; i++){
		for(int j = 0; j < 801; j++){
			d[i][j] = inf;
		}
	}
}

bool check(int i, int j, bool which){
	if(which == 1)
		{
		if(i >= 0 && i < n && j >= 0 && j < n && (a[i][j] == 'G' || a[i][j] == 'D') && !vis[i][j]){
			return 1;
		}
		return 0;
	}
	else{
		if(i >= 0 && i < n && j >= 0 && j < n && a[i][j] == 'G' && !vis[i][j]){
			return 1;
		}
		return 0;
	}
}

void bfs(){
	queue<pair<int, int>> q;
	for(auto x : allhives){
		q.push(x);
		d[x.first][x.second] = 0;
	}

	while(!q.empty()){
		pair<int, int> u = q.front(); q.pop();

		for(int i1 = 0; i1 < 4; i1++){
			int x = movex[i1], y = movey[i1];
			if(d[u.first + x][u.second + y] != inf)continue;
			if(check(u.first + x, u.second + y, 0)){
				d[u.first + x][u.second + y] = d[u.first][u.second] + 1;
				q.push({u.first + x, u.second + y});
				mx = max(mx, d[u.first + x][u.second + y]);
			}
		}
	}
}

bool possible(int x){
	int cur = x + 1;
	memset(vis, 0, sizeof vis);
	queue<pair<pair<int, int>, pair<int,int>>> q;

	q.push({{st.first, st.second}, {cur, s}});
	vis[st.first][st.second] = 1;

	while(!q.empty()){
		auto k = q.front(); q.pop();
		int u = k.first.first, v = k.first.second, chargesleft = k.second.second;
		int now = k.second.first;

		for(int i = 0; i < 4; i++){
			if(check(u + movex[i], v + movey[i], 1)){
				if(d[u + movex[i]][v + movey[i]] >= now){
					if(chargesleft > 1){
						q.push({{u + movex[i], v + movey[i]}, {now, chargesleft - 1}});
					}else{
						q.push({{u + movex[i], v + movey[i]}, {now + 1, s}});
					}
					vis[u + movex[i]][v + movey[i]] = 1;
				}
			}
		}
	}
	/*cout << "x : " << x << '\n';
	for(int i = 0; i < n; i++){
		for(int j = 0; j < n; j++){
			cout << vis[i][j];
		}
		cout << '\n';
	}*/
	if(vis[en.first][en.second])return 1;
	return 0;
}
int main(){
	cin >> n >> s;
	fill();

	for(int i = 0; i < n; i++){
		cin >> a[i];
	}
	for(int i = 0; i < n; i++){
		for(int j = 0; j < n; j++){
			if(a[i][j] == 'H'){
				allhives.push_back({i, j});
			}
			if(a[i][j] == 'M'){
				st.first = i;
				st.second = j;
			}
			if(a[i][j] == 'D'){
				en.first = i;
				en.second = j;
			}
		}
	}
	/*for(int i = 0; i < n; i++){
		for(int j = 0; j < n; j++){
			if(d[i][j] != inf)cout << d[i][j];
			else cout << 0;
		}
		cout << '\n';
	}*/
	bfs();
	int l = 0, r = mx;
	int ans = -1;
	while(l <= r){
		int mid = l + (r - l + 1) / 2;
		if(possible(mid)){
			l = mid + 1;
			ans = mid;
		}else{
			r = mid - 1;
		}
	}
	cout << ans << '\n';
}
#Verdict Execution timeMemoryGrader output
Fetching results...