您的位置:首页 > 产品设计 > UI/UE

HDU - 1242Rescue (以这道题为例,区分优先队列和队列的区别)

2019-06-11 18:10 1811 查看
版权声明:如需转载,私聊博主 https://blog.csdn.net/lylzsx20172018/article/details/91453053

题目链接:https://cn.vjudge.net/contest/306123#problem/E
解析:不管是bfs还是dfs,求出来的结果是最短路径,这题的不同之处在于杀死守卫时间加1,举个“栗子”,你bfs搜到的最短路径为4,可能这条路上都是守卫,那你就需要花费8,还不如路径是5,但这条路上没一个守卫花费的时间短,还有一点,题目虽说有多个(for each of angle’s friend)朋友,但根据测试就有一个朋友,可能天使的朋友被莫甘娜和华烨杀死了。

队列的操作:
1.定义结构体

struct node{
int x;
int y;
int step;
};
  1. 基本格式
queue<node>q;
node u,v;
q.push(u) //压入队列
q.front()  //访问首元素
q.pop()  //踢出队列

优先队列的操作:
1.定义结构体

struct node{
int x;
int y;
int step;
bool operator <(const node & n)const
{
return n.step<step;
}
};

2.基本操作

priority_queue<node>q;
node u,v;
q.push(u) //压入队列
u=q.top(); //访问首元素
q.pop()  //踢出队列

代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,flag;
char st[202][202];
int book[202][202];
int to[4][2]={-1,0,0,-1,1,0,0,1};
struct node{
int x;
int y;
int step;
bool operator <(const node & n)const
{
return n.step<step;
}
};
void bfs(int x,int y){
int mi;
book[x][y]=1;
priority_queue<node>q;
node u,v;
u.x=x,u.y=y,u.step=0;
q.push(u);
while(!q.empty()){
u=q.top();
if(st[u.x][u.y]=='a'){
flag=1;
mi=u.step;
break;
}
q.pop();
for(int i=0; i<4; i++){
int ex=u.x+to[i][0];
int ey=u.y+to[i][1];
if(ex<0||ex>=n||ey<0||ey>=m||st[ex][ey]=='#'||book[ex][ey]==1)
continue;
if(st[ex][ey]=='.'||st[ex][ey]=='a')
v.step=u.step+1;
if(st[ex][ey]=='x')
v.step=u.step+2;
v.x=ex,v.y=ey;
book[ex][ey]=1;
q.push(v);
}
}
if(flag)
printf("%d\n",mi);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main(){
int bx,by;
while(~scanf("%d %d",&n,&m)){
memset(book,0,sizeof(book));
flag=0;
for(int i=0; i<n; i++)
scanf("%s",st[i]);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(st[i][j]=='r'){
bx=i;
by=j;
break;
}
}
}
bfs(bx,by);
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: