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 }

 

posted @ 2021-04-24 17:00  acmloser  阅读(49)  评论(0编辑  收藏  举报