先介绍一下怎么在bfs里面怎么使用优先队列;、
**使用重载运算符**在结构体内使用;
struct node
{
int x, y, num;
friend bool operator<(node a, node b) {return a.num<b.num;}//大的优先;大于号小的优先
};
priority_queue<node> q;//这里无论是大的优先还是小的优先都这样些;因为重载运算符;
先看如果要使队列以结构体的某个元素小的优先出队列;
struct node
{
int x, y, num;
friend bool operator<(node a, node b) {return a.num>b.num;}//改成小于号就ok;;;
};
priority_queue<node> q;//这里无论是大的优先还是小的优先都这样些;因为重载运算符;
反之要使大的优先只需要把大于号改成小于号就ok;;;
看到题目;
hdu1242
题目链接;http://acm.split.hdu.edu.cn/showproblem.php?pid=1242;
题目大意;从r到a处;只能走点,每走一步需要一个时间;打怪x也需要一个时间;求最短的时间;
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
#include<algorithm>
#include<stack>
#include<set>
#include<string.h>
using namespace std;
char mp[202][202];
int mark[202][202];
int n, m,ri,rj,ai,aj;
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct node
{
int x, y, t;
friend bool operator<(node a, node b) {return a.t>b.t;}
};
void bfs()
{
int i,tt;
priority_queue<node>q;
node now,next;
memset(mark,0,sizeof(mark));
mark[ri][rj]=1;
now.x=ri;now.y=rj;now.t=0;
q.push(now);
while(!q.empty())
{
now = q.top();
q.pop();
for(i = 0; i < 4; i++)
{
next.x = now.x+dir[i][0];
next.y = now.y+dir[i][1];
if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&mark[next.x][next.y]==0&&mp[next.x][next.y]!='#')
{
tt=1;
if(mp[next.x][next.y]=='x')
tt=2;
next.t=now.t+tt;
mark[next.x][next.y]=1;
if(next.x==ai&&next.y==aj)
{
printf("%d\n",next.t);
return ;
}
q.push(next);
}
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
return ;
}
int main()
{
int i,j;
while(~scanf("%d %d",&n,&m))
{
for(i = 0; i < n; i++)
{
scanf("%s",mp[i]);
for(j = 0; j < m; j++)
{
if(mp[i][j]=='r'){
ri = i;
rj = j;
}
if(mp[i][j]=='a'){
ai = i;
aj = j;
}
}
}
// for(i = 0; i < n; i++)
// printf("%s\n",mp[i]);
// printf("ri=%d;rj=%d;ai=%d;aj=%d\n",ri,rj,ai,aj);
bfs();
}
return 0;
}