题解:P4779 【模板】单源最短路径(标准版)

· · 题解

题意

# 解析 在本题中,标准的 SPFA 由于特殊构造的数据,无法通过。所以,我们需要用另一种最短路算法:dijkstra。 ## 算法介绍 dijkstra 算法基于贪心的思想,常用来解决**非负权图**上的最短路问题。标准的 dijkstra 算法流程是: 1. 将 $dis_{s\to s}$ 设为 $0$,其他的设为 $+\infty$。 2. 遍历所有点,找到与起点距离最近且**未被标记过**的点,并标记它。 3. 扩展其能到达且**未被标记过**的点,更新他们的距离。 4. 不断重复 $2$、$3$ 过程,直到所有点都被标记。 这样的贪心策略在**非负权图**上是正确的。 ## 证明: > 假设节点 $u$ 现被标记且在被标记时距离不是最小值,则必然存在一条路径能够使得 $s\to u$ 的距离更短。但由于无负权,所以这条路径上的点到起点距离一定小于此时 $u$ 到起点的距离,则不可能先标记 $u$。故假设不成立,所以 $u$ 被标记时距离一定是最小值。 但是,在负权图上,会出现一些 BUG。例如下图: ![](https://cdn.luogu.com.cn/upload/image_hosting/n362ypz1.png) 显然,从 $1$ 到 $2$ 的最短路长度为 $2$,从 $1$ 到 $3$ 的最短路长度为 $-1$。 但 dijkstra 的贪心策略会导致扩展完 $2$,$3$ 两个节点后,先去标记 $3$ 号点,导致我们 $2$ 号点扩展时时无法再更新 $3$ 号点距离,如下图所示(图中用一个红色小叉号表示已被标记)。 ![](https://cdn.luogu.com.cn/upload/image_hosting/vvn6z6n7.png) ![](https://cdn.luogu.com.cn/upload/image_hosting/gatpcev3.png) ![](https://cdn.luogu.com.cn/upload/image_hosting/n32d4qvb.png) 所以,当遇到负权图时,要么老老实实地用 SPFA,要么就用势能 dijkstra,但还是要用到 SPFA。 回归正题,朴素 dijkstra 的时间复杂度是 $\mathcal{O}(n^2+m)$ 的,证明如下: > 每次扩展最多扩展 $n$ 个节点,一共有 $n$ 个点;每条边最多遍历一次,所以时间复杂度是 $\mathcal{O}(n^2+m)$。 容易发现,时间复杂度的瓶颈是在寻找距离最小的节点上,考虑优化。 不难发现,堆就有这么良好的性质,便于我们寻找距离最小的点,于是可以用堆优化:将每个被扩展到的节点扔到堆里,每次要找最小节点时取出堆顶,这样的时间复杂度为 $\mathcal{O}\!\left((n+m)\log n\right)$(不支持 decrease-key 或较慢)。证明如下: > 节点入堆共 $n$ 次,出堆共 $n$ 次,而为了扩展节点减少距离,还要有 $m$ 次为了减少距离而带来的入堆操作,共 $\mathcal{O}\!\left((n+m)\log n\right)$。 若你的堆支持 $\mathcal{O}(1)$ 的 decrease-key 的话,时间复杂度将进一步降到 $\mathcal{O}(n\log n+m)$。 在稀疏图上,肯定是堆优化版 dijkstra 更优,而在稠密图上,$\mathcal{O}(1)$ decrease-key 优于暴力版优于不支持 decrease-key 堆优化。 最后,把 AC 代码放一下吧。 ## [$\color{#009a00}\texttt{Accepcted}$](https://www.luogu.com.cn/record/201257545) $\texttt{Code}$ $\texttt{1}

使用 STL 中的堆。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define un unsigned
struct Node{
    int id,dis;
    Node(){}
    Node(const int &id,const int &dis){
        this->id=id;this->dis=dis;
    }
};
struct edge{
    int to,cost;
    edge(){}
    edge(const int &to,const int &cost){
        this->to=to;this->cost=cost;
    }
};
auto cmp=[](const Node&a,const Node&b)->bool{
    return a.dis>b.dis;
};
typedef pair<int,int> PII;
constexpr int maxn=1e5+3;
priority_queue<Node,vector<Node>,decltype(cmp)> q(cmp);
int n,m,s,dis[maxn];
bool vis[maxn];
vector<edge> e[maxn];
void dijkstra(){
    memset(dis,0x3f,sizeof dis);
    memset(vis,false,sizeof vis);
    dis[s]=0;
    q.push(Node(s,0));
    while(!q.empty()){
        int u=q.top().id;q.pop();
        if(vis[u]) continue;
        vis[u]=true;
        for(auto v:e[u]){
            if(vis[v.to]) continue;
            if(dis[v.to]>dis[u]+v.cost){
                dis[v.to]=dis[u]+v.cost;
                q.push(Node(v.to,dis[v.to]));
            }
        }
    }
    return;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cerr.tie(nullptr);
    cin>>n>>m>>s;
    for(int i=1;i<=m;i++){
        int u,v,w;cin>>u>>v>>w;
        e[u].push_back(edge(v,w));
    }
    dijkstra();
    for(int i=1;i<=n;i++) cout<<dis[i]<<' '; 
    return 0;
}

\color{#009a00}\texttt{Accepcted} \texttt{Code} \texttt{2}

手写堆(左偏树)。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define un unsigned
struct Node{
    int id,dis;
    Node(){}
    Node(const int &id,const int &dis){
        this->id=id;this->dis=dis;
    }
};
struct edge{
    int to,cost;
    edge(){}
    edge(const int &to,const int &cost){
        this->to=to;this->cost=cost;
    }
};
auto cmp=[](const Node&a,const Node&b)->bool{
    return a.dis>b.dis;
};
typedef pair<int,int> PII;
constexpr int maxn=1e5+3;
namespace COB{
    template<typename _Tp,typename _Cmp=std::less<_Tp>>
    class priority_queue{
        private:
            struct Node{
                Node *ch[2];
                _Tp val;
                int dist;
                Node():ch{nullptr,nullptr},val(_Tp()),dist(0){}
                Node(_Tp v):ch{nullptr,nullptr},val(v),dist(0){}
                ~Node(){ch[0]=ch[1]=nullptr;}
            };
            Node *root;
            _Cmp cmp;
            std::size_t sz;
            int dist(Node* p){
                return p==nullptr? -1:p->dist;
            }
            Node* merge(Node* x,Node* y){
                if(x==nullptr||y==nullptr) return (x==nullptr? y:x);
                if(cmp(x->val,y->val)) std::swap(x,y);
                x->ch[1]=merge(x->ch[1],y);
                if(dist(x->ch[0])<dist(x->ch[1])) std::swap(x->ch[0],x->ch[1]);
                x->dist=dist(x->ch[1])+1;
                return x;
            }
            void build(const Node* p){
                if(!p) return;
                build(p->ch[0]);
                build(p->ch[1]);
                root=merge(root,new Node(p->val));
                return;
            }
            void clear(Node*& p){
                if(!p) return;
                clear(p->ch[0]);
                clear(p->ch[1]);
                delete p;p=nullptr;
                return;
            }
        public:
            priority_queue(_Cmp comp=_Cmp()):root(nullptr),sz(0),cmp(comp){}
            priority_queue(const priority_queue& oth,_Cmp comp=_Cmp()){
                root=nullptr,sz=oth.sz,cmp=comp;
                build(oth.root);
            }
            priority_queue(const std::initializer_list<_Tp>& init,_Cmp comp=_Cmp()){
                root=nullptr,sz=init.size(),cmp=comp;
                for(const auto& i:init) root=merge(root,new Node(i));
            }
            priority_queue(std::priority_queue<_Tp> q){
                root=nullptr,sz=q.size();
                while(!q.empty()) root=merge(root,new Node(q.top())),q.pop();
            }
            ~priority_queue(){
                clear(root);
            }
            priority_queue& operator=(const priority_queue& q){
                clear(root);
                build(q.root);
                sz=q.size();
                return *this;
            }
            const _Tp& top()const{
                return root->val;
            }
            void push(const _Tp& x){
                ++sz;
                root=merge(root,new Node(x));
                return;
            }
            void pop(){
                --sz;
                Node *lc=root->ch[0],*rc=root->ch[1];
                delete root;
                root=merge(lc,rc);
                return;
            }
            void join(priority_queue& q){
                root=merge(root,q.root);
                q.root=nullptr;
                sz+=q.sz;
                q.sz=0;
                return;
            }
            void swap(priority_queue& q){
                std::swap(q.root,root);
                std::swap(q.sz,sz);
                return;
            }
            std::size_t size()const{return sz;}
            bool empty()const{return sz==0;}
            void clear(){
                sz=0;
                clear(root);
                return;
            }
    };
}
COB::priority_queue<Node,decltype(cmp)> q(cmp);
int n,m,s,dis[maxn];
bool vis[maxn];
vector<edge> e[maxn];
void dijkstra(){
    memset(dis,0x3f,sizeof dis);
    memset(vis,false,sizeof vis);
    dis[s]=0;
    q.push(Node(s,0));
    while(!q.empty()){
        int u=q.top().id;q.pop();
        if(vis[u]) continue;
        vis[u]=true;
        for(auto v:e[u]){
            if(vis[v.to]) continue;
            if(dis[v.to]>dis[u]+v.cost){
                dis[v.to]=dis[u]+v.cost;
                q.push(Node(v.to,dis[v.to]));
            }
        }
    }
    return;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cerr.tie(nullptr);
    cin>>n>>m>>s;
    for(int i=1;i<=m;i++){
        int u,v,w;cin>>u>>v>>w;
        e[u].push_back(edge(v,w));
    }
    dijkstra();
    for(int i=1;i<=n;i++) cout<<dis[i]<<' '; 
    return 0;
}

完结撒花!\ 你发现绿色的 Accepted 可以点了吗