Submission #621375

#TimeUsernameProblemLanguageResultExecution timeMemory
621375abcisosm5Mecho (IOI09_mecho)C++17
38 / 100
697 ms3008 KiB
#include <bits/stdc++.h>
using namespace std;
#define pi pair<int, int>
#define f first
#define s second

int N, S;
const int MN = 800;
char grid[MN][MN] = {{}};
vector<pi> hives;
pi M; pi D;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};

void movebees(queue<pi> (&b), char (&v)[MN][MN], int t){
	for(int i = 0; i < t; i++){
		queue<pi> nextb;
		while(!b.empty()){
			pi p = b.front(); b.pop();
			for(int d = 0; d < 4; d++){
				int nx = p.f + dx[d]; int ny = p.s + dy[d];
				if(nx < 0 || nx >= N || ny < 0 || ny >= N) continue;
				if(v[nx][ny] != 'B' && grid[nx][ny] == 'G'){
					v[nx][ny] = 'B';
					nextb.push({nx, ny});
				}
			}
		}
		b = nextb;
	}
}

bool movemecho(queue<pi> (&m), char (&v)[MN][MN]){
	for(int i = 0; i < S; i++){
		queue<pi> nextm;
		while(!m.empty()){
			pi p = m.front(); m.pop();
			for(int d = 0; d < 4; d++){
				int nx = p.f + dx[d]; int ny = p.s + dy[d];
				if(nx < 0 || nx >= N || ny < 0 || ny >= N) continue;
				if(!v[nx][ny] && grid[nx][ny] != 'T'){
					if(grid[nx][ny] == 'D') return true;
					v[nx][ny] = 'M';
					nextm.push({nx, ny});
				}
			}
		}
		m = nextm;
	}
	return false;
}

bool works(int t){ //O(N^2)
	char visited[MN][MN] = {{}};
	queue<pi> bees;
	for(pi p : hives){
		bees.push(p);
		visited[p.first][p.second] = 'B'; 
	}
	movebees(bees, visited, t);

	queue<pi> mecho; mecho.push(M); visited[M.f][M.s] = 'M';
	
	for(int i = 0; i < N*N/2; i++){
		//first, move mecho S steps
		if(mecho.empty()) break;
		bool success = movemecho(mecho, visited);
		if(success) return true;

		//then, move bees 1 step
		movebees(bees, visited, 1);
	}

	return false;
}

int main(){
	cin.tie(0)->sync_with_stdio(0);

	cin >> N >> S;

	for(int i = 0; i < N; i++){
		for(int j = 0; j < N; j++){
			cin >> grid[i][j];

			if(grid[i][j] == 'M') M = {i, j};
			if(grid[i][j] == 'D') D = {i, j};
			if(grid[i][j] == 'H') hives.push_back({i,j});
		}
	}

	int lo = -1; int hi = N*N/2; //amount of head start to bees

	while(lo < hi){ // in total, O(N^2 log N)
		int mid = lo + (hi - lo + 1) / 2;
		if(works(mid)){
			lo = mid;
		} else {
			hi = mid - 1;
		}
	}

	cout << lo;

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