HDU 4308 Saving Princess claire_

 

链接: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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值