No2.Djikstra + 堆优化

本文解析洛谷P1462通往奥格瑞玛的道路题,采用二分答案法结合最短路径算法,通过实例讲解如何解决最大最小问题。代码示例使用C++实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摸了快一个月的鱼我突然决定改过自新QwQ

单源最短路径....应该没人不知道

那么就用一道难度比模板大一些的题目来当例子吧

 

洛谷P1462 通往奥格瑞玛的道路

https://www.luogu.org/problemnew/show/P1462

 

看到“最大的最小”或者"最小的最大"时,基本可以确定是一道二分答案的题目了

#include<cstdio>
#include<queue>
#include<climits>
using namespace std;
inline int read(){
    int f = 1,x = 0;
    char c = getchar();
    while(c>'9' || c<'0'){if(c == '-')f = -1;c = getchar();}
    while(c<='9' && c>='0'){x = x*10 + c-'0';c = getchar();}
    return x * f;
}
const int MAXN = 10005;
const int MAXM = 50005;
const int INF = INT_MAX;//正无穷
int hp,n,m,cost[MAXN],l = INF,r;
//边 
struct Edge{
    int next,to,v;
}edge[MAXM<<1];
int head[MAXN],ecnt;
void addedge(int from,int to,int v){
    edge[++ecnt].next = head[from];
    edge[ecnt].to = to;
    edge[ecnt].v = v;
    head[from] = ecnt;
}
//输入数据 
void init(){
    n = read();m = read();hp = read();
    for(int i = 1;i <= n;i++){
        cost[i] = read();
        if(cost[i] > r)r = cost[i];
        if(cost[i] < l)l = cost[i]; 
    }
    int a,b,c;
    for(int i = 0;i < m;i++){
        a = read();b = read();c = read();
        if(a == b)continue;//注意题目中说的a可能等于b
        addedge(a,b,c);
        addedge(b,a,c);
    }
}
//点 
struct node{
    int pos,d;
    bool operator <(const node &x)const{
        return d > x.d;
    }
};
long long dist[MAXN];
bool dij(int x){
    priority_queue<node> que;
    for(int i = 1;i <= n;i++)dist[i] = INF;
    dist[1] = 0;
    que.push(node{1,0});
    while(!que.empty()){
        node temp = que.top();
        que.pop();
        int now = temp.pos;
        int d = temp.d;
        if(d != dist[now])continue;
        for(int i = head[now];i;i = edge[i].next){
            int to = edge[i].to;
            int v = edge[i].v;
            if(cost[to] > x)continue;//如果超过了上限就不走这个点
            if(dist[to] > dist[now] + v){
                dist[to] = dist[now] + v;
                que.push(node{to,dist[to]});
            }
        }
    }
    return dist[n] <= hp;//判断这条路走完还活不活着
    //因为是以血量为边权的最短路
    //所以不用担心有别的更少掉血的选择
}
int main(){
    init();
    int ans;
    if(!dij(r)){//注意要先判断是否为AFK
        printf("AFK");
        return 0;
    }
    while(l <= r){//二分答案
        int mid = (l + r) >> 1;
        if(dij(mid)){
            ans = mid;
            r = mid - 1 ;
        } 
        else l = mid + 1;
    }
    printf("%d",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值