P1340 优先队列做法

· · 题解

翻遍了题解区没发现有用优先队列的,全是逆序 kruskal,所以这里提供优先队列做法,时间复杂度有时甚至可以吊打逆序求解的做法。

其实就是每次加边时把边加入优先队列,然后做一遍 kruskal 就可以了。这样就免去了每次循环 sort 排序。时间复杂度为 O(W \times N + \log W) = O(W \times N)。

代码如下,注意一些细节,如优先队列遍历方法等。

#include<bits/stdc++.h>
using namespace std;
int n,W;
struct Node{
    int u,v,w;
    bool operator<(const Node& s) const {
        return w>s.w;//排序,可以理解为 cmp 函数
    }
};
priority_queue<Node>g;//存边的优先队列
int f[205];//并查集
int find(int x){
    if(f[x]==x) return x;
    else return f[x]=find(f[x]);
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>W;
    while(W--){
        int u,v,w;
        cin>>u>>v>>w;
        g.push({u,v,w});
        for(int i=1;i<=n;i++)
            f[i]=i;
        int ans=0,num=0;
        //ans是答案,num是联通块
        auto cur=g;//复制一遍,因为STL的优先队列无迭代器
        while(!cur.empty()){//遍历方法较vector有些许不同
            auto [u,v,w]=cur.top();
            if(find(u)==find(v)) {
                cur.pop();
                continue;
            }
            f[find(u)]=find(v);
            ans+=w;
            cur.pop();
            num++;
            if(num==n-1) break;//已经是一棵树了
        }
        if(num==n-1) cout<<ans<<'\n';//不联通
        else cout<<-1<<'\n';
    }

}

但缺点就是好像不能逆序求解了。