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

http://acm.hdu.edu.cn/showproblem.php?pid=1026

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

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

View Code
  1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 #include <iostream>
5 using namespace std;
6 const int max_s = 107;
7 const int N = 99999999;
8 struct node
9 {
10 int x,y;
11 int sum;
12 friend bool operator < (const node&a,const node&b)//比较函数
13 {
14 return a.sum>b.sum;
15 }
16 };
17 struct nn
18 {
19 int x,y;
20 }pre[max_s][max_s];
21 int f[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
22 char s[max_s][max_s];
23 int ptr[max_s][max_s];
24 priority_queue < node > Q;//优先队列的定义方式
25 int n,m,ans;
26 int bfs()
27 {
28 int i;
29 while(!Q.empty()) Q.pop();
30 node tmp,tx;
31 tmp.x=0;
32 tmp.y=0;
33 tmp.sum=0;
34 ptr[0][0]=0;
35 Q.push(tmp);
36 while(!Q.empty())
37 {
38 //puts("!!");
39 node t=Q.top();
40 Q.pop();
41 //printf("%d %d\n",t.x,t.y);
42 if(t.x==n-1&&t.y==m-1)
43 {
44 ans=t.sum;
45 return 1;
46 }
47 for(i=0;i<4;i++)
48 {
49 int a=t.x+f[i][0];
50 int b=t.y+f[i][1];
51 if(a>=0&&a<n&&b>=0&&b<m&&s[a][b]!='X')
52 {
53 tx.x=a;
54 tx.y=b;
55 tx.sum=t.sum+1;
56 if(s[a][b]!='.') tx.sum+=s[a][b]-'0';
57 if(ptr[a][b]>tx.sum)
58 {
59 ptr[a][b]=tx.sum;
60 pre[a][b].x=t.x;
61 pre[a][b].y=t.y;
62 Q.push(tx);
63 }
64 }
65 }
66 }
67 return 0;
68 }
69 void pf(int x,int y)//递归的输出
70 {
71 int i;
72 if(x==0&&y==0)
73 return ;
74 pf(pre[x][y].x,pre[x][y].y);
75 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);
76 if(s[x][y]!='.')
77 {
78 for(i=1;i<=s[x][y]-'0';i++)
79 {
80 printf("%ds:FIGHT AT (%d,%d)\n",ptr[pre[x][y].x][pre[x][y].y]+1+i,x,y);
81 }
82 }
83 }
84
85 int main()
86 {
87 //freopen("d.txt","r",stdin);
88 int i,j;
89 while(~scanf("%d%d",&n,&m))
90 {
91 for(i=0;i<n;i++)
92 scanf("%s",s[i]);
93 for(i=0;i<n;i++)
94 for(j=0;j<m;j++)
95 ptr[i][j]=N;
96 if(bfs())
97 {
98 printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
99 pf(n-1,m-1);
100 }
101 else
102 printf("God please help our poor hero.\n");
103 printf("FINISH\n");
104 }
105 return 0;
106 }



你可能感兴趣的:(优先队列)