题解:AT_abc481_d [ABC481D] Autopilot

· · 题解

题目传送门

题意:

给定 N 个星球和 M 条单向航线。飞船从当前星球出发,有两种移动方式:

  1. 免费移动:飞到当前星球能到达的所有星球中,编号最小的那个星球。

  2. 消耗燃料移动:花费 1 单位燃料,飞到任意一个当前星球能到达的星球。

求从起点 S 出发,到达终点 T 所需的最少燃料。如果不能到达,输出 -1。

分析:

常规的 BFS 或者 Dijkstra 很难直接处理“免费去最小的”这种带特殊条件的移动。但是,我们可以换个角度思考:能不能把这种“特殊移动”转化成图上的“特殊边权”?

我们可以把所有航线看成有向边,对每条边赋予 0 或 1 的边权:

这样一来,题目就转化成了:在一个边权只有 0 和 1 的图上,求从 S 到 T 的最短路。

因为边权只有 0 和 1,我们可以用 Dijkstra 或者 0-1 BFS。在这里我用了带有小根堆优化的 Dijkstra。

思路:

  1. 存图:用邻接表 vector<node> e[N] 存图。在存图的同时,记录每个星球 u 连出去的最小星球编号 mn[u],初始化为 INF。

  2. 更新边权:存完图后,遍历每一个星球 u 的所有出边。如果出边指向的星球 x.to 等于 \text{mn}_u,说明这是免费移动,把这条边的边权 x.w 改为 0;否则保持为 1。

  3. Dijkstra:

    • 初始化 dist 数组为极大值,dist[s] = 0。
    • 将起点 S 放入优先队列。
    • 每次取出当前代价最小的节点 u,遍历其所有的出边。如果通过 u 走到 v 的代价更小,则更新 dist[v] 并将其入队。
  4. 输出答案:如果 dist[t] 依然是极大值,说明无法到达,输出 -1;否则输出 dist[t]。

复杂度分析:

赛时AC记录:

AC代码:

#include<bits/stdc++.h>
#define int long long
#define rep(c,l,r) for (int c=l;c<=r;c++)
using namespace std;
const int N=200005;
struct node{

    int to,w;
};
vector<node> e[N]; //邻接表存图
int mn[N],dist[N]; //mn记录能到达的最小编号,dist记录最短代价

struct node2{ //优先队列的结构体,重载小于号,使代价小的优先出队

    int u,cst;
    bool operator<(const node2& st) const{
        return cst>st.cst;
    }
};

int dijkstra(int n,int s,int t){ //dijkstra

    rep(i,1,n){
        dist[i]=1e18; //初始化
    }
    dist[s]=0;

    priority_queue<node2> pq;
    pq.push({s,0});

    while(!pq.empty()){
        node2 cur=pq.top();
        pq.pop();

        int u=cur.u,cst=cur.cst;

        if(cst>dist[u]){ //如果当前取出的代价已经大于记录的最短路,直接跳过
            continue;
        }

        for(auto x:e[u]){ //遍历所有出边
            int v=x.to,w=x.w;

            if(dist[u]+w<dist[v]){ 
                dist[v]=dist[u]+w;
                pq.push({v,dist[v]});
            }
        }
    }

    if(dist[t]==1e18){
        return -1;
    }

    return dist[t];
}
signed main(){

    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int n,m,s,t;
    cin>>n>>m>>s>>t;

    rep(i,1,n){
        mn[i]=1e18; //初始化mn
    }

    rep(i,1,m){
        int u,v;
        cin>>u>>v;
        mn[u]=min(mn[u],v); //维护该点能到达的最小星球
        node x;
        x.to=v,x.w=1;
        e[u].push_back(x);
    }

    rep(i,1,n){ //将通往最小星球的边权改为0
        for(auto &x:e[i]){
            if(x.to==mn[i]){
                x.w=0;
            }
        }
    }

    cout<<dijkstra(n,s,t); //dijkstra求最短路

    return 0;
}