思路:多源BFS。
不要被这个名字所吓倒,其实就是BFS的一点稍微变形。
题目中的样例说,这个时候地图里面有两个传染源,然后给出了三个点,让其为领主,让你求这个领主最短时间能感染到什么程度。这里其实也就是让起点多了一个而已,然后就是对于这两个起点的扩散BFS遍历而已。
多源BFS的操作只需要我们将这两个起点提前入队就行了,然后再在这两个起点的基础上再进行扩散。即使是多个起点也是一样的
在我们BFS遍历之后,我们再去找领主在哪,这个时候我们的dist数组已经更新完数值了,所以我们只需要找领主的位置输出就行了。
上代码;
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include <iomanip>
#include<sstream>
#include<numeric>
#include<map>
#include<limits.h>
#include<set>
#define int long long
#define MAX 550
#define _for(i,a,b) for(int i=a;i<(b);i++)
#define ALL(x) x.begin(),x.end()
using namespace std;
typedef pair<int, int> PII;
int n, m;
int counts;
char maps[MAX][MAX];
int dist[MAX][MAX];
int a, b;
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
queue<PII>q;
void bfs() {
while (!q.empty()) {
auto tmp = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int a = dx[i] + tmp.first;
int b = dy[i] + tmp.second;
if (a <= 0 || a > n || b <= 0 || b > m)
continue;
if (dist[a][b] >= 0)
continue;
dist[a][b] = dist[tmp.first][tmp.second]+1;
q.push({ a,b });
}
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n >> m >> a >> b;
memset(dist, -1, sizeof dist);
while (a--)
{
int x, y;
cin >> x >> y;
dist[x][y] = 0;
q.push({ x,y });
}
bfs();
while (b--) {
int sta;
int end;
cin >> sta >> end;
cout << dist[sta][end] << endl;
}
return 0;
}