P1332 血色先锋队
P1332 血色先锋队 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)https://www.luogu.com.cn/problem/P1332
题目描述
军团是一个 n 行 m 列的矩阵,每个单元是一个血色先锋军的成员。感染瘟疫的人,每过一个小时,就会向四周扩散瘟疫,直到所有人全部感染上瘟疫。你已经掌握了感染源的位置,任务是算出血色先锋军的领主们感染瘟疫的时间,并且将它报告给巫妖王,以便对血色先锋军进行一轮有针对性的围剿。
输入格式
第 1 行:四个整数 n,m,a,b,表示军团矩阵有 n 行 m 列。有 a 个感染源,b 为血色敢死队中领主的数量。
接下来 a 行:每行有两个整数 x,y,表示感染源在第 x 行第 y 列。
接下来 b 行:每行有两个整数 x,y,表示领主的位置在第 x 行第 y 列。
输出格式
第 1 至 b 行:每行一个整数,表示这个领主感染瘟疫的时间,输出顺序与输入顺序一致。如果某个人的位置在感染源,那么他感染瘟疫的时间为 00。
输入输出样例
输入 #1
5 4 2 3 1 1 5 4 3 3 5 3 2 4
输出 #1
3 1 3
题目分析
在原来的广搜基础上做一个预处理即可--------多起点同时开始搜索(染色问题),除此之外,若该人员已经被感染记得跳过,最后在跑一边地图查找君主位置即可
代码示例
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
using ll = long long;
const int N = 510;
struct que{
int x, y;
};
int n, m, a, b;
int dist[N][N];
que q[N * N];
int hh = 0, tt = -1;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, 1, -1};
void bfs() {
while(hh <= tt) {
que t = q[hh++];
for(int i = 0; i < 4; i++) {
int a = t.x + dx[i], b = t.y + dy[i];
//方向遍历
if(a < 1 || a > n || b < 1 || b > m) continue;
if(dist[a][b] >= 1) continue;
//边界加感染跳过
dist[a][b] = dist[t.x][t.y] + 1;
tt++;
q[tt].x = a, q[tt].y = b;
}
}
}
int main() {
int x, y;
scanf("%d%d%d%d", &n, &m, &a, &b);
while(a--) {
scanf("%d %d", &x, &y);
tt++;
q[tt].x = x, q[tt].y = y;
dist[x][y] = 1;
}
bfs();
while(b--) {
scanf("%d %d", &x, &y);
printf("%d\n", dist[x][y] - 1);
}
return 0;
}
(顺道练个套皮c)