10分MLE求优化-必关
查看原帖
10分MLE求优化-必关
1270926
wawatime1楼主2024/10/26 18:14
#include <bits/stdc++.h>
using namespace std;
int a[511][511];
int n, m, c, d;
int dx[5] = {0, 0, 0, 1, -1}, dy[5] = {0, 1, -1, 0, 0};
void bfs (int x, int y) {
	queue <int> qx;
	queue <int> qy;
	queue <int> s;
	s.push (0);
	qx.push (x);
	qy.push (y);
	while (!qx.empty()) {
		if (a[qx.front()][qy.front()] == 1){
			printf ("%d\n", s.front());
			break;
		}
		for (int i = 1; i <= 4; i++) {
			int nx = qx.front() + dx[i];
			int ny = qy.front() + dy[i];
			if (nx >= 1 && nx <= n && ny >= 1 && ny <= m) {
				qx.push (nx);
				qy.push (ny);
				s.push (s.front() + 1);
			}
		}
		qx.pop();
		qy.pop();
		s.pop();
	}
}

int main() {
	scanf ("%d%d%d%d", &n, &m, &c, &d);
	for (int i = 1; i <= c; i++){
		int p, q;
		scanf ("%d%d", &p, &q);
		a[p][q] = 1;
	}
	for (int i = 1; i <= d; i++){
		int x, y;
		scanf ("%d%d", &x, &y);
		bfs (x, y);
	}

	return 0;
}

一天好心情

2024/10/26 18:14
加载中...