HDU 2612 Find a way(BFS)
生活随笔
收集整理的這篇文章主要介紹了
HDU 2612 Find a way(BFS)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=2612
題目大意:給你一張n*m的圖,圖上有兩個(gè)點(diǎn)Y、M,和若干個(gè)點(diǎn)@,找出某個(gè)點(diǎn)@使Y、M到這里的距離之和最小,并求出距離。
解題思路:BFS,求出Y、M到各個(gè)@的最小距離存下來(lái),最后枚舉各個(gè)@找出最小距離和即可。
代碼:
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 const int N=205; 7 8 int n,m,ans,cnt; 9 int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; 10 int vis[N][N],resy[N][N],resm[N][N]; 11 char map[N][N]; 12 13 struct node{ 14 int x,y,step; 15 }pre,now; 16 17 struct node2{ 18 int x,y; 19 }kfc[N*N]; 20 21 void bfs(int x,int y,int name){ 22 queue<node>q; 23 now.x=x; 24 now.y=y; 25 now.step=0; 26 q.push(now); 27 int num=0; 28 while(!q.empty()){ 29 pre=q.front(); 30 q.pop(); 31 for(int i=0;i<4;i++){ 32 int xx=pre.x+d[i][0]; 33 int yy=pre.y+d[i][1]; 34 if(xx<1||yy<1||xx>n||yy>m||map[xx][yy]=='#'||vis[xx][yy]) 35 continue; 36 //打表記錄Y、M到各個(gè)@點(diǎn)的最小距離 37 if(map[xx][yy]=='@'){ 38 num++; 39 if(name==1) 40 resy[xx][yy]=pre.step+1; 41 else 42 resm[xx][yy]=pre.step+1; 43 if(num==cnt) 44 return; 45 } 46 vis[xx][yy]=1; 47 now.x=xx; 48 now.y=yy; 49 now.step=pre.step+1; 50 q.push(now); 51 } 52 } 53 return; 54 } 55 56 int main(){ 57 while(~scanf("%d%d",&n,&m)){ 58 memset(vis,0,sizeof(vis)); 59 memset(resy,0x3f,sizeof(resy)); 60 memset(resm,0x3f,sizeof(resm)); 61 int sx,sy,sxx,syy; 62 cnt=0; 63 for(int i=1;i<=n;i++){ 64 getchar(); 65 for(int j=1;j<=m;j++){ 66 scanf("%c",&map[i][j]); 67 if(map[i][j]=='@') 68 kfc[++cnt].x=i,kfc[cnt].y=j; 69 if(map[i][j]=='Y') 70 sx=i,sy=j; 71 if(map[i][j]=='M') 72 sxx=i,syy=j; 73 } 74 } 75 bfs(sx,sy,1); 76 memset(vis,0,sizeof(vis)); 77 bfs(sxx,syy,2); 78 int ans=1<<30; 79 for(int i=1;i<=cnt;i++){ 80 int x=kfc[i].x; 81 int y=kfc[i].y; 82 ans=min(ans,resy[x][y]+resm[x][y]); 83 } 84 printf("%d\n",ans*11); 85 } 86 return 0; 87 }?
轉(zhuǎn)載于:https://www.cnblogs.com/fu3638/p/7521444.html
總結(jié)
以上是生活随笔為你收集整理的HDU 2612 Find a way(BFS)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 微信进行证书相关操作(退款,发放优惠券等
- 下一篇: 团队编程项目作业2-团队编程项目开发环境