首页 > 其他 > 详细

HDOJ 1242

时间:2014-02-05 00:03:01      阅读:518      评论:0      收藏:0      [点我收藏+]

纠结1242很久了,查了题解才发现要优先队列才能成功

http://blog.chinaunix.net/uid-21712186-id-1818266.html 使人开窍之文章

优先队列,已经不算是FIFO的队列了,而是一种以优先级(可以是值的大小等等)进行动态插入数值的一种“伪队列”,其中优先队列是用堆

而优先队列中与BFS的关系便在于,BFS的出队便是代表着

使用方法与队的方法差不多,(STL)

接下来是代码与解析

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int SIZE=300;
int M,N;
char map[SIZE][SIZE];
int x1,y1;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
typedef struct point
{
    int x,y;
    int t;
    bool operator < (const point &a)const // 对"<"符号的重定义
    {
        return t>a.t;
    }
}point;
int over(point a)
{
    if(a.x<0||a.y<0||a.x==N||a.y==M) return 1;
    return 0;
}//越界处理
int bfs()
{
    priority_queue<point> q;
    point sp,p,tmp;
    sp.x=x1;sp.y=y1;sp.t=0;
    map[sp.y][sp.x]=‘#‘;
    q.push(sp);
    while(!q.empty())
    {
        tmp=q.top();
        q.pop();
        for(int i=0;i<4;i++)
        {
            p.x=tmp.x+dir[i][0];
            p.y=tmp.y+dir[i][1];
            p.t=tmp.t+1;
            if(over(p)) continue;
            if(map[p.y][p.x]==‘#‘) continue;
            if(map[p.y][p.x]==‘r‘) return p.t;
            if(map[p.y][p.x]==‘.‘)
            {
                map[p.y][p.x]=‘#‘;
                q.push(p);
            }
            else
            {
                map[p.y][p.x]=‘#‘;
                p.t++;//精髓所在
                q.push(p);
            }
        }
    }
    return -1;
}
int main()
{
    //freopen("data.in","r",stdin);
    int i,j,ret;
    while(scanf("%d%d",&M,&N)!=EOF)
    {
        for(i=0;i<M;i++)
            scanf("%s",map[i]);
        for(i=0;i<M;i++)
            for(j=0;j<N;j++)
            if(map[i][j]==‘a‘)
            {
                x1=j;
                y1=i;
            }
        ret=bfs();
        if(ret==-1) printf("Poor ANGEL has to stay in the prison all his life.\n");
         else printf("%d\n",ret);
    }
    return 0;
}

http://blog.csdn.net/listeningsea/article/details/7718484

HDOJ 1242

原文:http://www.cnblogs.com/acalvin/p/3537953.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!