您的位置:首页 > 其它

hdu 1026 BFS+优先队列

2015-07-25 21:55 253 查看
初看这道题就有一种感觉:这道题是搜索,但是普通的搜索绝对会TLE,但是又实在想不到什么好的方法做。百度了一下解题报告才知道这道题要加上优先队列的优化,先从时间小的结点开始扩展,这样的话保证每个结点只被搜索一次,并且被搜索到的时候对于这个结点来说,时间是最少的,所以我们只需扩展到右下角就停止搜索,这样的话时间复杂度就可以接受了。

这道题由于要输出路径,所以采用一个数组标记,最后用递归的方法进行输出。

有一点需要注意,由于有多组测试数据,所以每次要对优先队列进行初始化,就是因为没有初始化,我调了一个晚上!

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

struct node
{
int ti,x,y;
friend bool operator < (node a,node b)
{
return a.ti>b.ti;
}
};

priority_queue<node>q;
int n,m,no;
bool f[105][105];
char a[105][105];

struct ROUTE
{
int x,y;
}r[105][105];

void bfs()
{
node w;
w.x=0; w.y=0; w.ti=0;
q.push(w);
r[0][0].x=-1; r[0][0].y=-1;
f[0][0]=1;
w=q.top();
while ((w.x!=n-1)||(w.y!=m-1))
{
int x=w.x,y=w.y,ti=w.ti+1;
node step;
if ((x>0)&&(a[x-1][y]!='X')&&(!f[x-1][y]))
{
f[x-1][y]=1;
step.x=x-1; step.y=y; step.ti=ti;
if (a[x-1][y]!='.') step.ti+=a[x-1][y]-'0';
q.push(step);
r[x-1][y].x=x;
r[x-1][y].y=y;
}
if ((x<n-1)&&(a[x+1][y]!='X')&&(!f[x+1][y]))
{
f[x+1][y]=1;
step.x=x+1; step.y=y; step.ti=ti;
if (a[x+1][y]!='.') step.ti+=a[x+1][y]-'0';
q.push(step);
r[x+1][y].x=x;
r[x+1][y].y=y;
}
if ((y>0)&&(a[x][y-1]!='X')&&(!f[x][y-1]))
{
f[x][y-1]=1;
step.x=x; step.y=y-1; step.ti=ti;
if (a[x][y-1]!='.') step.ti+=a[x][y-1]-'0';
q.push(step);
r[x][y-1].x=x;
r[x][y-1].y=y;
}
if ((y<m-1)&&(a[x][y+1]!='X')&&(!f[x][y+1]))
{
f[x][y+1]=1;
step.x=x; step.y=y+1; step.ti=ti;
if (a[x][y+1]!='.') step.ti+=a[x][y+1]-'0';
q.push(step);
r[x][y+1].x=x;
r[x][y+1].y=y;
}
q.pop();
if (q.empty()) break;
w=q.top();
}
if (q.empty()) {printf("God please help our poor hero.\n"); return;}
printf("It takes %d seconds to reach the target position, let me show you the way.\n",w.ti);
}

void print (int q,int w)
{
int x=r[q][w].x,y=r[q][w].y;
if (x<0) return;
print(x,y);
no++;
printf("%d",no);
printf("s:(%d,%d)->(%d,%d)\n",x,y,q,w);
if (a[q][w]=='X') return;
int z=0;
if (a[q][w]!='.') z=a[q][w]-'0';
for (int i=0;i<z;i++)
{
no++;
printf("%d",no);
printf("s:FIGHT AT (%d,%d)\n",q,w);
}
}

int main()
{
while (scanf("%d%d",&n,&m)!=EOF)
{
for (int i=0;i<n;i++) scanf("%s",a[i]);
while (!q.empty()) q.pop();
memset(f,0,sizeof(f));
bfs();
no=0;
if (!q.empty()) print(n-1,m-1);
printf("FINISH\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: