优先队列 模板

 1 /*
 2 优先队列
 3 */
 4 
 5 #include<stdio.h>
 6 #include<iostream>
 7 #include<cstdlib>
 8 #include<string.h>
 9 #include<queue>
10 #define HH 11111111
11 using namespace std;
12 char a[202][202];
13 int visit[202][202];
14 int n,m;
15 int map[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
16 struct node
17 {
18     friend bool operator< (node n1,node n2)
19     {
20         return n1.p>n2.p;
21     }
22     int p;
23     int x;
24     int y;
25 };
26 void bfs(int x,int y)
27 {
28     int i,x1,y1;
29     priority_queue<node>b;
30     while(!b.empty())
31     {
32         b.pop();
33     }
34     node tmp,tmp1;
35     tmp.x=x;
36     tmp.y=y;
37     tmp.p=0;
38     b.push(tmp);
39     visit[x][y]=1;
40     while(b.size()>0)
41     {
42         tmp=b.top();
43         b.pop();
44         for(i=0;i<4;i++)
45         {
46             x1=tmp.x+map[i][0];
47             y1=tmp.y+map[i][1];
48             if(x1>=1&&x1<=n && y1>=1&&y1<=m && visit[x1][y1]==0 && a[x1][y1]!='#')
49             {
50                 if(a[x1][y1]=='x')
51                     visit[x1][y1]=tmp.p+2;
52                 else if(a[x1][y1]=='.' || a[x1][y1]=='r')
53                     visit[x1][y1]=tmp.p+1;
54                 tmp1=tmp;
55                 tmp.x=x1;
56                 tmp.y=y1;
57                 tmp.p=visit[x1][y1];
58                 b.push(tmp);
59                 tmp=tmp1;
60                 if(a[x1][y1]=='r')return;
61             }
62         }
63     }
64 }
65 int main()
66 {
67     int i,j,num;
68     while(scanf("%d%d",&n,&m)>0)
69     {
70         for(i=1;i<=n;i++)
71             scanf("%s",a[i]+1);
72         memset(visit,0,sizeof(visit));
73         for(i=1;i<=n;i++)
74             for(j=1;j<=m;j++)
75             {
76                 if(a[i][j]=='a')
77                 {
78                     bfs(i,j);
79                 }
80             }
81         num=HH;
82         for(i=1;i<=n;i++)
83             for(j=1;j<=m;j++)
84             {
85                 if(a[i][j]=='r' && visit[i][j]!=0 && visit[i][j]<num)
86                     num=visit[i][j];
87             }
88         if(num==HH)
89             printf("Poor ANGEL has to stay in the prison all his life.
");
90         else
91             printf("%d
",num);
92     }
93     return 0;
94 }
原文地址:https://www.cnblogs.com/tom987690183/p/3446421.html