题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4308
Sample Input
1 3 3
Y*C
1 3 2
Y#C
1 5 2
YP#PC
Sample Output
3
Damn teoy!
0
题目大意是王子拯救公主,Y为王子起点,C为公主位置,*是收费站,经过要花费一定的金钱,#是障碍,P是传送门,可以传送到任意一个P,问王子能否救到公主,如果能最小花费是多少
题解:
个人觉得这是一道不错bfs广搜入门题目,基本是bfs的模板题,除了要注意一下,当搜到P时,要对全部坐标搜一遍,将其余P全部送入队列中,因为这样找到路径才是最短,由于收费站花费一样所以也是花费最少。
代码如下:,
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cstring> #include<cmath> int start[2][2]; bool vis[5000][5000]; using namespace std; struct coord { int x1; int y1; int nu; } c; queue<coord> q; int bfs(char **s,int i,int j,int money) { int ans=money*i*j; while(!q.empty()) q.pop(); int dir[4][2]= {-1,0,0,-1,0,1,1,0}; c.x1=start[0][0]; c.y1=start[0][1]; c.nu=0; int x2=start[1][0],y2=start[1][1]; q.push(c); while(!q.empty()) { int x3=q.front().x1,y3=q.front().y1; //cout<<s[x3][y3]<<' '<<cost[num]<<endl; for(int a=0; a<4; a++) { int x=x3+dir[a][0]; int y=y3+dir[a][1]; if(x>=0&&y>=0&&x<i&&y<j&&s[x][y]!='#'&&!vis[x][y]&&s[x][y]!='Y') { //cout<<s[x][y]<<' '<<cost[num]<<endl; if(x==x2&&y==y2) ans=min(q.front().nu,ans); else if(s[x][y]=='P') { c.x1=x; c.y1=y; //cout<<cost[num]<<endl; c.nu=q.front().nu; vis[x][y]=true; q.push(c); for(int b=0; b<i; b++) for(int d=0; d<j; d++) if(s[b][d]=='P') { if(b==x&&d==y) continue; else { c.x1=b; c.y1=d; c.nu=q.front().nu; vis[b][d]=true; q.push(c); } } } else if(s[x][y]=='*') { c.x1=x; c.y1=y; c.nu=q.front().nu+money; vis[x][y]=true; q.push(c); } } } q.pop(); } return ans; } int main() { int r,f,money; while(scanf("%d %d %d",&r,&f,&money)!=EOF) { char **s=(char **)malloc(r*sizeof(char*)); getchar(); memset(s,0,sizeof(s)); memset(start,0,sizeof(start)); memset(vis,false,sizeof(vis)); for(int i=0; i<r; i++) {s[i]=(char *)malloc(f*sizeof(char)); for(int j=0; j<f; j++) { scanf("%c",&s[i][j]); if(s[i][j]=='Y') { start[0][0]=i; start[0][1]=j; } else if(s[i][j]=='C') { start[1][0]=i; start[1][1]=j; } } getchar(); } int ans=bfs(s,r,f,money); if(ans>=money*r*f) printf("Damn teoy!\n"); else printf("%d\n",ans); for(int i=0; i<r; i++) free(s[i]); free(s); } return 0; }