P5195 [USACO05DEC]Knights of Ni S
考察:bfs
思路:
存下所有草药的坐标,对于每一个草药求贝茜和骑士到达它的时间,每个时间遍历求最小值.
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 using namespace std; 5 const int N = 1010,INF = 0x3f3f3f3f; 6 typedef pair<int,int> PII; 7 int xx[4] = {-1,1,0,0},yy[4] ={0,0,-1,1}; 8 int n,m,mp[N][N],sx,sy,ex,ey,cnt; 9 int dist[2][N][N]; 10 PII p[N*N]; 11 void bfs(int a,int b,int idx) 12 { 13 memset(dist[idx],0x3f,sizeof dist[idx]); 14 queue<PII> q; 15 dist[idx][a][b] = 0; 16 q.push({a,b}); 17 while(q.size()) 18 { 19 PII it = q.front(); 20 q.pop(); 21 int x = it.first,y = it.second; 22 for(int i=0;i<4;i++) 23 { 24 int dx = x+xx[i],dy = y+yy[i]; 25 if(dx>0&&dx<=n&&dy>0&&dy<=m&&mp[dx][dy]!=1&&dist[idx][dx][dy]==INF) 26 { 27 dist[idx][dx][dy] = dist[idx][x][y]+1; 28 q.push({dx,dy}); 29 } 30 } 31 } 32 } 33 int main() 34 { 35 scanf("%d%d",&m,&n); 36 for(int i=1;i<=n;i++) 37 for(int j=1;j<=m;j++) 38 { 39 scanf("%d",&mp[i][j]); 40 if(mp[i][j]==2) sx = i,sy = j; 41 else if(mp[i][j]==3) ex = i,ey = j; 42 else if(mp[i][j]==4) p[++cnt] = {i,j}; 43 } 44 mp[ex][ey] = 1; 45 bfs(sx,sy,0); 46 mp[ex][ey] = 3; 47 bfs(ex,ey,1); 48 int ans = INF; 49 for(int i=1;i<=cnt;i++) 50 { 51 int x = p[i].first,y = p[i].second; 52 ans = min(ans,dist[0][x][y]+dist[1][x][y]); 53 } 54 printf("%d\n",ans); 55 return 0; 56 }
分类:
ACM / 搜索
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了