BZOJ 1671: [Usaco2005 Dec]Knights of Ni 骑士 (bfs)
题目:
https://www.lydsy.com/JudgeOnline/problem.php?id=1671
题解:
按题意分别从贝茜和骑士bfs然后meet_in_middle。。
把一个逗号打成分号调了20分钟。。。
代码:
1 #include<bits/stdc++.h>
2
3 using namespace std;
4
5 const int mx[5]={0,-1,1,0,0},my[5]={0,0,0,-1,1};
6 const int maxn=1010;
7 int n,m,g[maxn][maxn],vis[maxn][maxn],f[maxn][maxn],sum,cnt,sx,sy,bx,by,flag,ans=0x3f3f3f3f;
8 struct node{int x,y,num;};
9
10 int main(){
11 scanf("%d%d",&m,&n);
12 for(int i=1;i<=n;i++)
13 for(int j=1;j<=m;j++){
14 scanf("%d",&g[i][j]);
15 if(g[i][j]==2) sx=i,sy=j;
16 else if(g[i][j]==3) bx=i,by=j;
17 else if(g[i][j]==4) sum++;
18 }
19 queue<node> q; cnt=sum;
20 q.push((node){sx,sy,0}),vis[sx][sy]=1;
21 while(!q.empty()){
22 node now=q.front(); q.pop();
23 for(int i=1;i<=4;i++){
24 int xx=now.x+mx[i],yy=now.y+my[i];
25 if(xx>0&&xx<=n&&yy>0&&yy<=m&&!vis[xx][yy]&&g[xx][yy]!=1){
26 if(g[xx][yy]==4&&f[xx][yy]==0) f[xx][yy]=now.num+1,cnt--;
27 if(!cnt) goto end;
28 q.push((node){xx,yy,now.num+1}); vis[xx][yy]=1;
29 }
30 }
31 }
32 end: memset(vis,0,sizeof(vis));
33 while(!q.empty()) q.pop(); cnt=sum;
34 q.push((node){bx,by,0}),vis[bx][by]=1;
35 while(!q.empty()){
36 node now=q.front(); q.pop();
37 for(int i=1;i<=4;i++){
38 int xx=now.x+mx[i],yy=now.y+my[i];
39 if(xx>0&&xx<=n&&yy>0&&yy<=m&&!vis[xx][yy]&&g[xx][yy]!=1){
40 if(g[xx][yy]==4) ans=min(now.num+1+f[xx][yy],ans),cnt--;
41 if(!cnt) goto print;
42 q.push((node){xx,yy,now.num+1}); vis[xx][yy]=1;
43 }
44 }
45 }
46 print: printf("%d",ans);
47 return 0;
48 }