Vas_Sago 2016-08-03 08:58 采纳率: 100%
浏览 1533
已采纳

RQNOJ PID34/ 紧急援救(用BFS+优先队列还超时)

 #include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<sstream>
#include<set>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<ctime>
#include<fstream>
#include<iomanip>
using namespace std;

#define M 1005

int n,m,a,b,X,Y;
int vis[M][M],flag=0;

char ma[M][M];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int num=1;

struct state
{
    int x,y,step;
    friend bool operator<(state x1,state x2){
        return x1.step>x2.step;  //优先队列,按照步数从小到大排列(最小优先队列)
    }
};

bool check(int x,int y)
{
    if(x<1||y<1||x>n||y>n||vis[x][y]||ma[x][y]=='1')
        return 1;
    return 0;
}

void BFS()
{
    if(flag)
        return ;
    priority_queue <state> Q;
    state st,next;
    st.x=a;
    st.y=b;
    st.step=0;
    Q.push(st);
    vis[a][b]=1;
    while(!Q.empty())
    {
        st=Q.top();
        Q.pop();
        if(st.x==X&&st.y==Y){
            flag=1;
            cout<<st.step<<endl;
            return ;
        }
        for(int i=0;i<4;i++)
        {
            next.x=st.x+dir[i][0];
            next.y=st.y+dir[i][1];
            if(check(next.x,next.y))
                continue;
            if(!vis[next.x][next.y])
            {
                //cout<<"Case:"<<num++<<" "<<next.x<<" "<<next.y<<endl;
                vis[next.x][next.y]=1;
                if(ma[next.x][next.y]=='0')
                    next.step=st.step+1;
                Q.push(next);
            }
        }
    }
    return ;
}

int main()
{
    cin>>n;
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            cin>>ma[i][j];
    cin>>a>>b>>X>>Y;
    BFS();
    return 0;
}
  • 写回答

1条回答

  • Vas_Sago 2016-08-03 09:34
    关注

    。。。不用优先队列就过了,服了,坑了几个钟头

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决