您的位置:首页 > 其它

hdu 1026 Ignatius and the Princess I(bfs+优先队列)

2011-11-26 11:47 483 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1026

才开始自己不清楚什么优先队列,就是直接从终点出发搜索直到找到出发点,记录最近。结果wa很多次,最后问了一下被人,才发现,最短的时间不是单调的每一步还要加上打怪的时间,yy了一下只要在每次出队列之前从小到大排一下队列里面的元素就行了啊。可是我的编码能力可能别太弱了结果没实现,于是就学习了stl中的优先队列的写法,stl 好强大啊。。

思路:bfs,优先队列,pre数组记录后继元素,,ptr数组记录到该点的时间,最后递归尚未输出结果(这个地方很难想到,很巧妙)。。

View Code

#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
const int max_s = 107;
const int N = 99999999;
struct node
{
int x,y;
int sum;
friend bool operator < (const node&a,const node&b)//比较函数
{
return a.sum>b.sum;
}
};
struct nn
{
int x,y;
}pre[max_s][max_s];
int f[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
char s[max_s][max_s];
int ptr[max_s][max_s];
priority_queue < node > Q;//优先队列的定义方式
int n,m,ans;
int bfs()
{
int i;
while(!Q.empty()) Q.pop();
node tmp,tx;
tmp.x=0;
tmp.y=0;
tmp.sum=0;
ptr[0][0]=0;
Q.push(tmp);
while(!Q.empty())
{
//puts("!!");
node t=Q.top();
Q.pop();
//printf("%d %d\n",t.x,t.y);
if(t.x==n-1&&t.y==m-1)
{
ans=t.sum;
return 1;
}
for(i=0;i<4;i++)
{
int a=t.x+f[i][0];
int b=t.y+f[i][1];
if(a>=0&&a<n&&b>=0&&b<m&&s[a][b]!='X')
{
tx.x=a;
tx.y=b;
tx.sum=t.sum+1;
if(s[a][b]!='.') tx.sum+=s[a][b]-'0';
if(ptr[a][b]>tx.sum)
{
ptr[a][b]=tx.sum;
pre[a][b].x=t.x;
pre[a][b].y=t.y;
Q.push(tx);
}
}
}
}
return 0;
}
void pf(int x,int y)//递归的输出
{
int i;
if(x==0&&y==0)
return ;
pf(pre[x][y].x,pre[x][y].y);
printf("%ds:(%d,%d)->(%d,%d)\n",ptr[pre[x][y].x][pre[x][y].y]+1,pre[x][y].x,pre[x][y].y,x,y);
if(s[x][y]!='.')
{
for(i=1;i<=s[x][y]-'0';i++)
{
printf("%ds:FIGHT AT (%d,%d)\n",ptr[pre[x][y].x][pre[x][y].y]+1+i,x,y);
}
}
}

int main()
{
//freopen("d.txt","r",stdin);
int i,j;
while(~scanf("%d%d",&n,&m))
{
for(i=0;i<n;i++)
scanf("%s",s[i]);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
ptr[i][j]=N;
if(bfs())
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
pf(n-1,m-1);
}
else
printf("God please help our poor hero.\n");
printf("FINISH\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: