题意:骑士,就暂且叫他骑士,要去就城堡里的公主。题意是,找到即为救到。在路上可能遇到一些小怪,遇到怪就要打咯,需要花费相应的时间。
解题思路:广搜+结构体记录路径+优先队列
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026
View Code
#include <iostream> using namespace std; const int MAX =100+10; #include <queue> bool used[MAX][MAX];//标记该坐标是否呗更新过 int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//方向坐标 #include <stack> struct node// { int i; int j;//更新的坐标 char ch;//当前坐标的字符 int sum;//走到当前坐标所需要花费的最小时间 friend bool operator<(node a,node b)//优先队列 { return a.sum>b.sum; } }; struct nodd// { int i; int j;//记录起父亲节点的值 int sum;//走到当前点的值 int x; int y;//当前点 }; int n,m; node a[MAX][MAX]; void bfs() { priority_queue<node>q; stack<nodd>s; node temp; memset(used,false,sizeof(used)); temp.i=0; temp.j=0; temp.sum=0; used[temp.i][temp.j]=true; q.push(temp); while(!q.empty()) { node flag=q.top(); q.pop(); for(int i=0;i<4;i++)//往四个方向搜 { node type=flag; type.i+=dir[i][0]; type.j+=dir[i][1]; if(type.i>=0&&type.i<n&&type.j>=0&&type.j<m&&a[type.i][type.j].ch!='X'&&!used[type.i][type.j])//判断是否满足要求 { a[type.i][type.j].i=flag.i; a[type.i][type.j].j=flag.j;//记录父亲节点 if(a[type.i][type.j].ch>'0'&&a[type.i][type.j].ch<='9')//遇到小怪,打小怪花费的时间 { type.sum+=a[type.i][type.j].ch-'0'; } used[type.i][type.j]=true; ++type.sum; if(type.i==n-1&&type.j==m-1)//判断是否找到 { int k=type.sum; nodd typ; typ.i=type.i; typ.j=type.j; for(int j=k;j>=1;j--) { typ.x=typ.i; typ.y=typ.j; if(a[typ.i][typ.j].ch>'0'&&a[typ.i][typ.j].ch<='9')//该点是否为小怪出现的点 { int x; nodd ty; for(x=j;x>j-a[typ.i][typ.j].ch+'0';x--) { ty.i=-1; ty.x=typ.i; ty.y=typ.j; ty.sum=x; s.push(ty); } j=x; } typ.i=a[typ.x][typ.y].i; typ.j=a[typ.x][typ.y].j; typ.sum=j; s.push(typ); } printf("It takes %d seconds to reach the target position, let me show you the way.\n",type.sum); while(!s.empty()) { if(s.top().i!=-1) { printf("%ds:(%d,%d)->(%d,%d)\n",s.top().sum,s.top().i,s.top().j,s.top().x,s.top().y); } else printf("%ds:FIGHT AT (%d,%d)\n",s.top().sum,s.top().x,s.top().y); s.pop(); } printf("FINISH\n"); return; } q.push(type); } } } printf("God please help our poor hero.\nFINISH\n"); return; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { getchar(); memset(used,false,sizeof(used)); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { scanf("%c",&a[i][j].ch); } getchar(); } bfs(); } return 0; }
吐槽一下:题目的广搜部分不是很难,关键是记录路径。做到半夜3点半,没做出来就没继续下了。体现出了编程的魅力真的很大,最开心的莫过于做出来的那一刻,最悲催的莫过于那个过程,不过彩虹总在风雨后。
停不下的脚步,停不下的喜悦,过程是那么让人发狂。