您的位置:首页 > 其它

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:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: