zoukankan      html  css  js  c++  java
  • 营救天使(优先队列)

    http://www.cnblogs.com/summerRQ/articles/2470130.html
    普通队列的出队方式是对头出列
    优先队列这则是按照一定的优先级出队的就好比医院里面急诊病人优先看病
    看下面一道题可以帮助理解优先队列
    http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1335

    /*
    题意:
    a被困在监狱他的朋友r想要去救他 里面有士兵x遇到士兵时r可以杀掉他,但是会耗时一分钟
    ,结果要输出救到a的最少时间

    注意:
    4 3
    .r#
    .x#
    .##
    a##
    有一种情况是不走x比走x花费的时间少,,()坑

    */

    include

    include<string.h>

    include

    include<stdio.h>

    include<stdlib.h>

    include<math.h>

    const int XY=205;
    char miGong[XY][XY];
    int vis[XY][XY];
    int dir[4][2]= {0,1,1,0,0,-1,-1,0};
    int m,n;
    using namespace std;
    struct note
    {
    int x;
    int y;
    int s;
    friend bool operator <(note n1,note n2)//自己定义一种优先级
    {
    return n1.s>n2.s;//时间少的优先级高(注意大于或小于号)
    }
    };
    int bfs(int sx,int sy,int ex,int ey)
    {
    memset(vis,0,sizeof(vis));
    note a;
    a.x=sx;
    a.y=sy;
    a.s=0;
    vis[sx][sy]=1;
    priority_queueq;
    q.push(a);
    while(!q.empty())
    {
    a=q.top();//注意不是q.front();
    q.pop();
    // cout<<miGong[a.x][a.y]<<" ";
    if(a.xex&&a.yey)return a.s;
    for(int i=0; i<4; i++)
    {
    int tx=a.x+dir[i][0];
    int ty=a.y+dir[i][1];
    if(tx<0||ty<0||tx>=m||ty>=n)
    continue;
    if(miGong[tx][ty]!='#'&&vis[tx][ty]0)
    {
    vis[tx][ty]=1;
    note b;
    b.x=tx;
    b.y=ty;
    if(miGong[tx][ty]
    'x')
    b.s=a.s+2;
    else b.s=a.s+1;
    q.push(b);
    }
    }
    }
    return -1;
    }
    int main()
    {

    while(~scanf("%d%d",&m,&n))
    {
        memset(miGong,0,sizeof(miGong));
        int startX,startY,endX,endY;
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
            {
                scanf(" %c",&miGong[i][j]);
                if(miGong[i][j]=='r')
                {
                    startX=i;
                    startY=j;
                }
                if(miGong[i][j]=='a')
                {
                    endX=i;
                    endY=j;
                }
            }
        int b=bfs(startX,startY,endX,endY);
        if(b==-1 )
            printf("Poor ANGEL has to stay in the prison all his life.
    ");
        else
            printf("%d
    ",b);
    }
    return 0;
    

    }

    /*
    4 3
    .r#
    .x#
    .##
    a##

    */

    梦里不知身是客,一晌贪欢。
  • 相关阅读:
    二分查找:思路很简单,细节是魔鬼
    今天遇到了 X-Y PROBLEM
    《工匠精神》读书笔记
    养成好的职业习惯
    php xdebug 调试
    Dockerfile的常见命令
    docker制作镜像
    脱坑笔记
    Java中代理
    2、遇到多个构造器参数的时候要考虑使用构建器
  • 原文地址:https://www.cnblogs.com/dccmmtop/p/5303302.html
Copyright © 2011-2022 走看看