链接:http://acm.hdu.edu.cn/showproblem.php?pid=4308
题意:一个r*c的迷宫,公主被困在C位置,王子从Y位置开始去就公主,#不能通过,*可以通过,但要花费cost元,P可以从该位置直接跳到其他P位置且免费。问能否救到公主,如果能,最小花费是多少。
分析:优先队列BFS,或转化成最短路做。
Source Code:
#include<algorithm>
#include<iostream>
#include<string>
#include<cstdio>
#include<queue>
using namespace std;
struct point{
int x,y;
}p[1000];
struct node{
int x,y,cost;
node(){}
node(int a,int b,int c):x(a),y(b),cost(c){}
bool friend operator <(node n1,node n2){
return n1.cost>n2.cost;
}
};
int n,m,cst,yx,yy,totp;
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
string Map[5004];
bool OK(int x,int y){
if(x>=0&&x<n&&y>=0&&y<m&&Map[x][y]!='#') return true;
return false;
}
int bfs(){
node cur;
int tx,ty;
priority_queue<node>Q;
Q.push(node(yx,yy,0));
Map[yx][yy]='#';
while(!Q.empty()){
cur=Q.top();
Q.pop();
for(int i=0;i<4;i++){
tx=cur.x+dx[i];
ty=cur.y+dy[i];
if(OK(tx,ty)){
if(Map[tx][ty]=='C') return cur.cost;
else if(Map[tx][ty]=='*'){
Map[tx][ty]='#';
Q.push(node(tx,ty,cur.cost+cst));
}
else{
for(int j=0;j<totp;j++){
Q.push(node(p[j].x,p[j].y,cur.cost));
Map[p[j].x][p[j].y]='#';
}
}
}
}
}
return -1;
}
int main()
{
while(cin>>n>>m>>cst){
totp=0;
for(int i=0;i<n;i++){
cin>>Map[i];
for(int j=0;j<m;j++){
if(Map[i][j]=='P'){
p[totp].x=i;
p[totp].y=j;
totp++;
}
else if(Map[i][j]=='Y'){
yx=i,yy=j;
}
}
}
int ans=bfs();
if(ans==-1) cout<<"Damn teoy!"<<endl;
else cout<<ans<<endl;
}
return 0;
}