码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1429胜利大逃亡(续)BFS+状态压缩

时间:2014-09-13 12:09:15      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:io   os   ar   for   sp   on   c   html   amp   

这题的算是BFS中应用状压的一个模板题吧,没啥难度,用key来存储已获得的钥匙,状压一下就可以了

不过我写的过程中,犯了好多SB错误,导致调试了好久才A,本来仔细可以1A的说

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#include <string>
#include <iostream>
#include <cstdlib>
#include <list>
#include <set>
#include <queue>
#include <stack>
using namespace std;
#define INF 0xfffffff
#define maxn 30
int n,m,t;
int vis[maxn][maxn][1500];
int dir[4][2]={-1,0,0,-1,1,0,0,1};
struct point
{
    int x,y;
    int state,key;
}s;
char map[maxn][maxn];
int bfs()
{
    memset(vis,0,sizeof(vis));
    queue<point>q;
    q.push(s);
    vis[s.x][s.y][0]=1;
    while(!q.empty())
    {
        point u=q.front();
        q.pop();
        point tmp;
        //printf("//%d %d//\n",u.x,u.y);
        for(int i=0;i<4;i++)
        {
            tmp.x=u.x+dir[i][0];
            tmp.y=u.y+dir[i][1];
            tmp.key=u.key;
            tmp.state=u.state+1;
            //printf("x=%d y=%d key=%d state=%d\n",tmp.x,tmp.y,tmp.key,tmp.state);
            if(tmp.state>=t||tmp.x<0||tmp.x>n-1||tmp.y<0||tmp.y>m-1||map[tmp.x][tmp.y]=='*') continue;
            char tc=map[tmp.x][tmp.y];
            if(tc=='^') return tmp.state;
            if(tc>='A'&&tc<='J')
            {
                //printf("%d %d\n",tmp.key,1<<(tc-'A'));
                if((tmp.key&(1<<(tc-'A')))==0) continue;//等于号前面的括号不要忘记打,在这里我都快调哭了
            }
            else if(tc>='a'&&tc<='j')
            {
                tmp.key|=(1<<(tc-'a'));
            }
            if(vis[tmp.x][tmp.y][tmp.key]==0)
            {
                vis[tmp.x][tmp.y][tmp.key]=1;
                //printf("rudui:%d %d\n",tmp.x,tmp.y);
                q.push(tmp);
            }
        }
    }
    return -1;
}
int main()
{
    while(scanf("%d%d%d",&n,&m,&t)!=EOF)
    {
        for(int i=0;i<n;i++)
        {
            scanf("%s",map[i]);
            for(int j=0;j<m;j++)
            {
                if(map[i][j]=='@')
                {
                    s.x=i;
                    s.y=j;
                }
            }
        }
        s.key=0;s.state=0;
        int ans=bfs();
        if(ans==-1) printf("-1\n");
        else if(ans<t) printf("%d\n",ans);
        else printf("-1\n");
    }
    return 0;
}


HDU1429胜利大逃亡(续)BFS+状态压缩

标签:io   os   ar   for   sp   on   c   html   amp   

原文地址:http://blog.csdn.net/u013748887/article/details/39249753

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!