codeforces 591 E (bfs and bf)
来源:互联网 发布:南京市行知基地 编辑:程序博客网 时间:2024/05/29 10:27
题目链接:点击打开链接
如果某点在最后生成的图上,那么它到各states的距离最短
直接对所有states进行BFS,计算它到图中各地所用最短距离
最后扫描整个图,取最小值即可
AC代码如下:
#include <iostream>#include <cstring>#include <algorithm>#include <queue>using namespace std;int n, m;char mapp[1005][1005];int dp[3][1005][1005];int isValid(int x, int y){ return x>=1&&x<=n&&y>=1&&y<=m&&mapp[x][y]!='#';}void wandering(char b){ int num = b-'1'; queue<pair<int, int>> qqq; for(int i=1; i<=n; ++i) for(int j=1; j<=m; ++j) { if(mapp[i][j]==b) qqq.push(make_pair(i,j)), dp[num][i][j]=0; else dp[num][i][j]=(int)1e8; } while(!qqq.empty()) { int x=qqq.front().first, y=qqq.front().second; qqq.pop(); if(isValid(x+1,y)&&dp[num][x+1][y] > dp[num][x][y]+(mapp[x][y]=='.')) {dp[num][x+1][y] = dp[num][x][y]+(mapp[x][y]=='.'); qqq.push(make_pair(x+1,y));} if(isValid(x,y+1)&&dp[num][x][y+1] > dp[num][x][y]+(mapp[x][y]=='.')) {dp[num][x][y+1] = dp[num][x][y]+(mapp[x][y]=='.'); qqq.push(make_pair(x,y+1));} if(isValid(x,y-1)&&dp[num][x][y-1] > dp[num][x][y]+(mapp[x][y]=='.')) {dp[num][x][y-1] = dp[num][x][y]+(mapp[x][y]=='.'); qqq.push(make_pair(x,y-1));} if(isValid(x-1,y)&&dp[num][x-1][y] > dp[num][x][y]+(mapp[x][y]=='.')) {dp[num][x-1][y] = dp[num][x][y]+(mapp[x][y]=='.'); qqq.push(make_pair(x-1,y));} }}void solve(){ int re = 1e9; for(int i=1;i<=n;++i) for(int j=1;j<=m;++j) re = min(re,dp[0][i][j]+dp[1][i][j]+dp[2][i][j]+(mapp[i][j]=='.')); /*for(int t=0;t<3;++t) { for(int i=1;i<=n;++i) { for(int j=1;j<=m;++j) cout<<dp[t][i][j]<<" "; cout<<endl; } cout<<'\n'<<endl; }*/ cout<<((re>=1e8)?-1:re)<<endl;}int main(){ ios::sync_with_stdio(0); cin.tie(0); while(cin>>n>>m) { memset(mapp,'#',sizeof(mapp)); for(int i=1; i<=n; ++i) for(int j=1; j<=m; ++j) cin>>mapp[i][j]; wandering('1'); wandering('2'); wandering('3'); solve(); } return 0;}
阅读全文
0 0
- codeforces 591 E (bfs and bf)
- Codeforces 653E (BFS set)
- codeforces-gym-100187-E【bfs】
- Codeforces E. Two Labyrinths ( BFS
- Codeforces 591E Three States【优先队列Bfs+思维】
- Codeforces 100187E:Two Labyrinths(搜索&&BFS)
- codeforces 152E bfs+状态压缩
- CodeForces - 525D Arthur and Walls(bfs)
- CodeForces 525D D. Arthur and Walls(BFS)
- Codeforces #325 D. Phillip and Trains (bfs)
- Codeforces 689B. Mike and Shortcuts(BFS)
- 【CodeForces】510B - Fox And Two Dots(bfs)
- 【CodeForces 510B】 Fox And Two Dots (dfs+bfs)
- Codeforces 877 D. Olya and Energy Drinks (bfs)
- POJ 1860 Currency Exchange 最短路 BF & SPFA(bfs)
- Codeforces 276E Little Girl and Problem on Trees【线段树+Bfs序+Dfs序】好题!
- Codeforces 362E Petya and Pipes (费用流)
- Codeforces 387E George and Cards(二分+树状数组)
- java 自定义mvc框架(一)------前端控制器的实现
- 康威定律
- 欢迎使用CSDN-markdown编辑器
- SQLiteStudio连接Android真机报无法连接ADB的错误解决办法
- Set,List,Map 集合
- codeforces 591 E (bfs and bf)
- bwboundaries
- 2017/9/14
- 关于SSM框架的session使用
- SpringBoot 不显示Whitelabel Error Page
- 1043. Is It a Binary Search Tree (25)
- Linux下logrotate日志轮询操作梳理
- 位置式和增量式PID
- java线程池介绍(一)