题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242
简单优先队列搜索,自己好久不敲,,,,,手残啊,,,,orz
代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <ctype.h>
#include <iomanip>
#include <queue>
#include <stdlib.h>
using namespace std; int N,M,ans;
char mp[][];
int vis[][]; int dx[]={,,-,};
int dy[]={-,,,}; int sx,sy;
int ex,ey; struct Node
{
int x,y;
int step;
}; bool operator<(Node a,Node b)//定义结构体类型的优先队列的优先级,从小到大
{
return a.step>b.step;
} void getMap(int n,int m)
{
for(int i=;i<n;i++)
for(int j=;j<m;j++)
{
cin>>mp[i][j];
if(mp[i][j]=='r')
{
sx=i;
sy=j;
}
if(mp[i][j]=='a')
{
ex=i;
ey=j;
}
}
} bool pd(int x,int y)
{
if(x>=&&x<N&&y>=&&y<M&&!vis[x][y]&&mp[x][y]!='#')
return true;
return false;
} int bfs(int x,int y)
{
memset(vis,,sizeof(vis));
priority_queue<Node>q;
Node a,b;
a.x=x,a.y=y,a.step=;
q.push(a);
while(!q.empty()){
b=q.top();
q.pop();
for(int i=; i<; i++){
int px=b.x+dx[i];
int py=b.y+dy[i];
if(pd(px,py)){
vis[px][py]=;
a.x=px;
a.y=py;
if(mp[px][py]=='x'){
a.step=b.step+;
q.push(a);
}
else
{
a.step=b.step+;
q.push(a);
if(px==ex && py==ey)
return a.step;
}
}
}
}
return -;
} int main()
{ while(cin>>N>>M){
getMap(N,M);
int ans=bfs(sx,sy);
if(ans==-)
printf("Poor ANGEL has to stay in the * all his life.\n");
else
printf("%d\n",ans);
}
}
优先队列搜索:
///优先队列是默认int从大到小priority_queue<int>q1,也可以定义为从小到大priority_queue<int,vector<int>,greater<int> >q2;
也可以自定义优先级,重载< #include <iostream>
#include <functional>
#include <queue>
using namespace std; ///自定义优先级,两种写法,按照优先级从大到小的顺序
/*
struct node
{
friend bool operator<(node n1,node n2)
{
return n1.priority<n2.priority;
}
int priority;
int value;
};*/ struct node
{
int priority;
int value;
};
bool operator<(node a,node b)
{
return a.priority<b.priority;
} int main()
{
const int len=;
int i;
int a[len]={,,,,};
//优先队列中从大到小输出
priority_queue<int>q1;
for(i=;i<len;i++)
q1.push(a[i]);
for(int i=;i<len;i++)
{
cout<<q1.top();
q1.pop();
}
cout<<endl;
//优先队列中从小到大输出 /**
priority_queue<int,vector<int>,greater<int> >q2;
for(i=0;i<len;i++)
q2.push(a[i]);
for(i=0;i<len;i++)
{
cout<<q2.top();
q2.pop();
}*/ priority_queue<int,vector<int>,greater<int> >q;
for(int i=;i<len;i++)
q.push(a[i]);
while(!q.empty())
{
cout<<q.top();
q.pop();
}
cout<<endl;
//按照某个优先级输出,该代码中为priority值大的先输出
priority_queue<node>q3;
node b[len];
b[].priority=;b[].value=;
b[].priority=;b[].value=;
b[].priority=;b[].value=;
b[].priority=;b[].value=;
b[].priority=;b[].value=;
for(i=;i<len;i++)
q3.push(b[i]);
cout<<"优先级"<<'\t'<<"值"<<endl;
for(i=;i<len;i++)
{
cout<<q3.top().priority<<'\t'<<q3.top().value<<endl;
q3.pop();
}
return ;
}
可见链接:http://blog.****.net/sr_19930829/article/details/42706469
运行:
96532
23569
优先级 值
9 5
8 2
6 1
2 3
1 4