洛谷 P2349 金字塔 题解

题目链接

题目描述

有一盗墓者潜入一金字塔盗宝。当她(难道是Lara Croft ?)打开一个宝箱的时候,突然冒出一阵烟(潘多拉的盒子?),她迅速意识到形势不妙,三十六计走为上计……由于她盗得了金字塔的地图,所以她希望能找出最佳逃跑路线。地图上标有N个室,她现在就在1室,金字塔的出口在N室。她知道一个秘密:那阵烟会让她在直接连接某两个室之间的通道内的行走速度减半。她希望找出一条逃跑路线,使得在最坏的情况下所用的时间最少。

题解

这道题可以用A*来做

估价函数由两个值组成:该节点到终点的最短距离和当前已经经过路径的最大值(在代码里估价函数为g,实际距离为step,当前节点位置为x,已经经过路径的边权的最大值为maxx)

代码

#include < cstdio >
#include < cstring >
#include < algorithm >
#include < queue>
using namespace std;
const int maxn=100005;
struct Node
{
    int to,next,dis;
} edge[maxn<<1];
struct node
{
    int g,step,maxx,x;
    bool operator < (node xx) const
    {
        return xx.g<g;
    }
};
int k=0,head[maxn],n,m,a,b,c,dist[maxn];
bool visit[maxn];
void add(int u,int v,int w)
{
    edge[++k].to=v;
    edge[k].next=head[u];
    edge[k].dis=w;
    head[u]=k;
}
void spfa()
{
    memset(dist,0x7f7f7f7f,sizeof(dist));
    queue<int> q;visit[n]=true;q.push(n);dist[n]=0;
    while(!q.empty())
    {
        int x=q.front();q.pop();visit[x]=false;
        for(int i=head[x];i;i=edge[i].next)
        {
            if(dist[edge[i].to]>dist[x]+edge[i].dis)
            {
                dist[edge[i].to]=dist[x]+edge[i].dis;
                if(!visit[edge[i].to])
                {
                    visit[edge[i].to]=true;
                    q.push(edge[i].to);
                }
            }
        }
    }
}
void Astar()
{
    priority_queue<node> q;node temp;temp.step=0;
    temp.g=dist[1];temp.maxx=0;temp.x=1;q.push(temp);
    while(!q.empty())
    {
        node now=q.top();q.pop();
        if(now.x==n)
        {
            printf("%d\n",now.step+now.maxx);
            return;
        }
        for(int i=head[now.x];i;i=edge[i].next)
        {
            temp.step=now.step+edge[i].dis;
            temp.maxx=max(now.maxx,edge[i].dis);
            temp.g=temp.step+temp.maxx+dist[edge[i].to];
            temp.x=edge[i].to;q.push(temp);
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);add(b,a,c);
    }
    spfa();
    Astar();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值