P1332 血色先锋队
题目大意
行列矩阵中, 有个已经被感染的人, 有个未感染的人, 求未感染的人被感染的时间, 如果一个人在感染源上, 则感染时间为0。
输入格式
第一行输入:
接下来行:每行输入已被感染的人的位置 行列
接下来行:每行输入未被感染的人的位置 行列
输出格式
按输入顺序每行输出未被感染的人被感染的时间
输入样例:
输出样例
数据范围
如图:(图片来自洛谷)
思路:
很明显是一道bfs题目,而且这还是一道很好的题目,因为我们平时常见的都是一个起点到一个终点,或者一个起点到多个终点的那种题目,而这个就不一样了,是多个起点到多个终点。
首先我第一思路就是对每个传染源都进行搜索,那么距离我们就可以取最小的那个距离,得出最终结果。
代码:
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 510;
int n, m, a, b;
int res[N][N], backups[N][N]; //res存放最优解 后者为备份数组
int virus[N][N];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void bfs(int x, int y)
{
queue<PII> q;
q.push({x, y});
memset(backups, -1, sizeof backups); //备份
backups[x][y] = 0;
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int xx = t.first + dx[i], yy = t.second + dy[i];
if(xx >= 1 && xx <= n && yy >= 1 && yy <= m && backups[xx][yy] == -1)
{
backups[xx][yy] = backups[t.first][t.second] + 1;
q.push({xx, yy});
res[xx][yy] = min(backups[xx][yy], res[xx][yy]);
}
}
}
}
int main()
{
queue<PII> q;
memset(res, 0x3f, sizeof res);
scanf("%d%d%d%d", &n, &m, &a, &b);
while(a--) //病毒
{
int x, y;
scanf("%d%d", &x, &y);
virus[x][y] = -1; //传染源表示为-1
bfs(x, y);
}
while(b--) //领主
{
int x, y;
scanf("%d%d", &x, &y);
q.push({x, y});
if(virus[x][y] == -1) res[x][y] = 0;
}
while(q.size())
{
auto t = q.front();
q.pop();
cout << res[t.first][t.second] << endl;
}
return 0;
}
然后就。。了。
然后再仔细想一下的性质,这题不是完美的符合嘛,完全可以搜一遍就好了,让所有的感染源都入队,同时标记为被感染,然后直接就可以了,搜到的点都进行标记,表示已经被感染。
什么,怕搜到的不是最短距离? 拜托!想想是干嘛的,第一次搜到的就是最优解啊,还有必要去搜一遍更新一遍嘛,没有必要!
这道题也是学到了hh。
emmm~还有就是数据范围大的时候用 和 避免不必要的
代码:
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 510, M = 1e5+10;
int n, m, a, b;
int res[N][N]; //res存放最优解 后者为备份数组
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
bool vis[N][N];
queue<PII> q;
void bfs()
{
while(q.size())
{
auto t = q.front();
q.pop();
vis[t.first][t.second] = true;
for(int i = 0; i < 4; i++)
{
int x = t.first + dx[i], y = t.second + dy[i];
if(x >= 1 && x <= n && y >= 1 && y <= m && !vis[x][y])
{
vis[x][y] = true;
res[x][y] = res[t.first][t.second] + 1;
q.push({x, y});
}
}
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &a, &b);
while(a--) //病毒
{
int x, y;
scanf("%d%d", &x, &y);
q.push({x, y}); //入队
vis[x][y] = true;
}
bfs();
for(int i = 1; i <= b; i++)
{
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", res[x][y]);
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端