Submission #401905

#TimeUsernameProblemLanguageResultExecution timeMemory
401905jli12345Mecho (IOI09_mecho)C++14
100 / 100
498 ms6560 KiB
#include <bits/stdc++.h>
using namespace std;

int N, S;

char arr[810][810];

int sx, sy, ex, ey;

typedef pair<int, int> pii;
#define f first
#define s second

queue<pair<pii, int> > q1;
queue<pair<pii, int> > q2;

int vis1[810][810];
int vis2[810][810];

const int INF = 0x3f3f3f3f;

int xd[4] = {1, -1, 0, 0};
int yd[4] = {0, 0, 1, -1};

void bfs(int t){
	while (!q2.empty()){
		int x = q2.front().f.f;
		int y = q2.front().f.s;
		int w = q2.front().s;
		if (w == t)
			break;
		q2.pop();
		for (int k = 0; k < 4; k++){
			int nx = x+xd[k];
			int ny = y+yd[k];
			if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && 
				arr[nx][ny] != 'T' && arr[nx][ny] != 'D'){
				if (vis2[nx][ny] > vis2[x][y]+1){
					vis2[nx][ny] = vis2[x][y]+1;
					q2.push({{nx, ny}, vis2[nx][ny]});
				}
			}
		}
	}
}

bool valid(int t){
	while (!q1.empty()) q1.pop();
	while (!q2.empty()) q2.pop();
	memset(vis1, INF, sizeof(vis1));
	memset(vis2, INF, sizeof(vis2));
	for (int i = 1; i <= N; i++){
		for (int j = 1; j <= N; j++){
			if (arr[i][j] == 'H'){
				q2.push({{i, j}, 0});
				vis2[i][j] = 0;
			}
		}
	}
	q1.push({{sx, sy}, 0});
	vis1[sx][sy] = 0;
	int curtime = 1;
	while (curtime <= t){
		bfs(curtime);
		curtime++;
	}
	while (!q1.empty()){
		int x = q1.front().f.f;
		int y = q1.front().f.s;
		int w = q1.front().s;
		if (x == ex && y == ey){
			return true;
		}
		if (vis1[x][y] == (curtime-t)*S){
			bfs(curtime);
			curtime++;
		}
		q1.pop();
		if (vis2[x][y] != INF){
			continue;
		}
		for (int k = 0; k < 4; k++){
			int nx = x+xd[k];
			int ny = y+yd[k];
			if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && vis2[nx][ny] == INF && 
				(arr[nx][ny] == 'D' || arr[nx][ny] == 'G')){
				if (vis1[nx][ny] > vis1[x][y]+1){
					vis1[nx][ny] = vis1[x][y]+1;
					q1.push({{nx, ny}, vis1[nx][ny]});
				}
			}
		}
	}
	return false;
}

int main(){
	cin >> N >> S;
	for (int i = 1; i <= N; i++){
		for (int j = 1; j <= N; j++){
			cin >> arr[i][j];
			if (arr[i][j] == 'M'){
				sx = i;
				sy = j;
			}
			if (arr[i][j] == 'D'){
				ex = i;
				ey = j;
			}
		}
	}
	if (!valid(0)){
		cout << -1 << "\n";
		return 0;
	}
	int l = 0, r = 640000;
	while (l != r){
		int mid = (l+r+1)/2;
		if (valid(mid)){
			l = mid;
		} else {
			r = mid-1;
		}
	}
	cout << l << "\n";
}

Compilation message (stderr)

mecho.cpp: In function 'bool valid(int)':
mecho.cpp:70:7: warning: unused variable 'w' [-Wunused-variable]
   70 |   int w = q1.front().s;
      |       ^
#Verdict Execution timeMemoryGrader output
Fetching results...