HDU 3582 BFS

来源:互联网 发布:数据结构考研算法 编辑:程序博客网 时间:2024/05/21 09:57

点击打开链接

题意:迷宫从起点走到终点,问能否走到,K是钥匙,L是门,每个钥匙只能用一次然后*是障碍,点是空地

思路:这题开始写到AC竟然错了30+,20+的MLE,因为自己写SB了,先说说我MLE的经验把,对于一把钥匙来说,我只能捡一次但是对于不同状态来的是要区分的,之前我写的就是不管什么状态来的我都要把钥匙捡起来,MLE,发现后又WA了几发,我们在队列里的状态要把哪个钥匙捡起来做个标记,防止上面说的错误,然后对于每个门来说,则可以用状态压缩来搞定,这题过的真心爽,刚开始MLE的我都要怀疑人生了,大神们怎么可以只用100多K就过了,我还在MLE,还好放了几天后脑袋清醒了很多,终于过了

#include <queue>#include <stdio.h>#include <iostream>#include <string.h>#include <stdlib.h>#include <algorithm>using namespace std;typedef long long ll;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const ll INF=0x3f3f3f3f3f3f3f3fll;const int maxn=15;int sx,sy,ex,ey,n,m,cnt;int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};bool vis[maxn][maxn][1030][100];char str[maxn][maxn];struct edge{    int x,y,step,flag,ss;    char str1[maxn][maxn];};struct snake{    int x,y;}sna[maxn*maxn];int bfs(){    queue<edge>que;    edge c,ne;    memset(vis,0,sizeof(vis));    str[sx][sy]='.';str[ex][ey]='.';    c.x=sx,c.y=sy,c.step=0;c.flag=0;c.ss=0;    for(int i=0;i<n;i++){        for(int j=0;j<m;j++){            c.str1[i][j]='.';        }    }    vis[c.x][c.y][0][0]=1;    que.push(c);    while(!que.empty()){        c=que.front();que.pop();        if(c.flag<c.step) continue;        if(c.x==ex&&c.y==ey) return 1;        for(int i=0;i<4;i++){            int xx=c.x+dir[i][0];            int yy=c.y+dir[i][1];            if(xx<0||xx>n-1||yy<0||yy>m-1||str[xx][yy]=='*') continue;            if(vis[xx][yy][c.ss][c.flag]) continue;            ne.x=xx;ne.y=yy;ne.step=c.step;ne.flag=c.flag;ne.ss=c.ss;            for(int ll=0;ll<n;ll++) strcpy(ne.str1[ll],c.str1[ll]);            if(str[xx][yy]=='L'){                for(int i=0;i<cnt;i++){                    if(xx==sna[i].x&&yy==sna[i].y){                        if((ne.ss>>i)&1){                            ne.step=c.step;                        }else{                            ne.step=c.step+1;                            ne.ss+=(1<<i);                        }                        break;                    }                }            }            if(str[xx][yy]=='K'){                if(c.str1[xx][yy]=='.') ne.flag=c.flag+1;                ne.str1[xx][yy]='*';            }            vis[ne.x][ne.y][ne.ss][ne.flag]=1;            que.push(ne);        }    }    return -1;}int main(){    int T,cas=1;    scanf("%d",&T);    while(T--){        scanf("%d",&n);        m=n;cnt=0;        for(int i=0;i<n;i++) scanf("%s",str[i]);        for(int i=0;i<n;i++){            for(int j=0;j<m;j++){                if(str[i][j]=='S') sx=i,sy=j;                if(str[i][j]=='E') ex=i,ey=j;                if(str[i][j]=='L'){                    sna[cnt].x=i;                    sna[cnt++].y=j;                }            }        }        int ans=bfs();        if(ans==-1) printf("Case %d: No\n",cas++);        else printf("Case %d: Yes\n",cas++);    }    return 0;}

0 0