HDU-#4771 Stealing Harry Potter's Precious(bfs+状态压缩)
2014-10-21 12:17
453 查看
题目大意:给出k个宝物的坐标,从起点开始依次到达所有宝物的点取走宝物的最短时间。
解题思路:由于走过的点还可以走,并且要求取走所有的最短时间,因此利用bfs去搜索最短的步骤,用状态压缩来记录走过的状态,每次更新取走所有的花费。详见code。
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=4771
code:
解题思路:由于走过的点还可以走,并且要求取走所有的最短时间,因此利用bfs去搜索最短的步骤,用状态压缩来记录走过的状态,每次更新取走所有的花费。详见code。
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=4771
code:
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; const int MAXN = 100+10; const int inf = 0x3fffffff; int n,m,k,sx,sy,ans; int vis[MAXN][MAXN][10][50]; char g[MAXN][MAXN]; int dir[4][2]={1,0,0,1,-1,0,0,-1}; struct node{ int x,y,step,cnt,status; }; void bfs(){ queue<node> q; node s; q.push((node){sx,sy,0,0,0}); while(!q.empty()){ s=q.front();q.pop(); int x=s.x,y=s.y,d=s.step,ct=s.cnt,st=s.status; if(ct==k) ans=min(ans,d); if(vis[x][y][ct][st]!=0) continue; vis[x][y][ct][st]=1; for(int i=0;i<4;++i){ int tx=x+dir[i][0]; int ty=y+dir[i][1]; int tmp=g[tx][ty]-'0'; if(tmp>=0 && tmp<k){ if(1<<tmp & st) q.push((node){tx,ty,d+1,ct,st}); else q.push((node){tx,ty,d+1,ct+1,(1<<tmp) | st}); } else if(tx>0 && tx<=n && ty>0 && ty<=m && g[tx][ty]!='#') q.push((node){tx,ty,d+1,ct,st}); } } } int main(){ //freopen("in.txt","r",stdin); while(~scanf("%d%d",&n,&m) && n+m){ memset(g,0,sizeof(g)); memset(vis,0,sizeof(vis)); for(int i=1;i<=n;++i){ scanf("%s",g[i]+1); for(int j=1;j<=n;++j) if(g[i][j]=='@'){ sx=i;sy=j; } } scanf("%d",&k); int x,y; for(int i=0;i<k;++i){ scanf("%d%d",&x,&y); g[x][y]='0'+i; } ans=inf; bfs(); if(ans!=inf) printf("%d\n",ans); else printf("-1\n"); } return 0; }
相关文章推荐
- BFS+状态压缩 hdu-1885-Key Task
- hdu 1429 胜利大逃亡(续) (bfs+状态压缩)
- hdu 1429 (bfs+状态压缩)
- HDU 1885 BFS+状态压缩
- hdu 5094 Maze (bfs+状态压缩)
- BFS+状态压缩 hdu-1885-Key Task
- HDU_4856_Tunnels(BFS+状态压缩)
- hdu 5025 Saving Tang Monk (bfs+状态压缩)
- hdu 4856 Tunnels(bfs+状态压缩)
- HDU 1429 BFS+状态压缩
- BFS+状态压缩 hdu-1429 胜利大逃亡(续)
- HDU 3681 Prison Break(BFS+二分+状态压缩DP)
- hdu 1429 胜利大逃亡(续) bfs+状态压缩
- HDU-#5025 Saving Tang Monk(BFS+状态压缩)
- poj1482 & hdu1818 It's not a Bug, It's a Feature!(bfs+状态压缩)
- hdu 1429 BFS+状态压缩
- hdu 2209 翻纸牌游戏(BFS+状态压缩)
- hdu 1429(bfs+状态压缩)
- hdu~1429(bfs+状态压缩)
- HDU 4568 Hunter BFS+状态压缩(才13个点)