【BFS】 HDU 4308 Saving Princess claire_

原题直通车:HDU 4308 Saving Princess claire_

分析: 两次BFS分别找出‘Y’、‘C’到达最近的‘P’的最小消耗。再算出‘Y’到‘C’的最小消耗,比较出最小值

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
using namespace std;
const int inf=0xFFFFFFF;
int n,m,k;
char f[5005][5005];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
int dis[5005][5005];
struct node{
    int x,y,cost;
    node(int a,int b,int c){
        x=a, y=b, cost=c;
    }
};
int BFS(node st,node et,int &p){
    queue<node>M;
    M.push(st);
    while(!M.empty()){
        node rt=M.front(); M.pop();
        if(f[rt.x][rt.y]==f[et.x][et.y]) return rt.cost;
        for(int i=0;i<4;++i){
            node ne=rt;
            ne.x+=dx[i], ne.y+=dy[i];
            if(ne.x<0||ne.y<0||ne.x>=n||ne.y>=m||f[ne.x][ne.y]=='#') continue;
            if(f[ne.x][ne.y]=='P'){
                if(p>ne.cost) p=ne.cost;
                continue;
            }
            if(f[ne.x][ne.y]=='*') ne.cost+=k;
            if(ne.cost<dis[ne.x][ne.y]){
                dis[ne.x][ne.y]=ne.cost;
                M.push(ne);
            }
        }
    }
    return -1;
}
int main(){
    while(~scanf("%d%d%d",&n,&m,&k)){
        int ci,cj,yi,yj;
        for(int i=0;i<n;++i){
            scanf("%s",f[i]);
            for(int j=0;j<m;++j){
                if(f[i][j]=='C')
                    ci=i, cj=j;
                else if(f[i][j]=='Y')
                    yi=i, yj=j;
                dis[i][j]=inf;
            }
        }
        node cc(ci,cj,0), yy(yi,yj,0);
        int cp=inf, yp=inf;
        int t1=BFS(cc,yy,cp);
        int t2=BFS(yy,cc,yp);
        if(t1==-1){
            if(cp!=inf&&yp!=inf) printf("%d\n",cp+yp);
            else puts("Damn teoy!");
        }
        else {
            if(cp!=inf&&yp!=inf&&t1>cp+yp) printf("%d\n",cp+yp);
            else printf("%d\n",t1);
        }
    }
    return 0;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值