luogu_1550【题解】打井(最小生成树)

题目:https://www.luogu.org/problemnew/show/P1550

设第n+1号点是水源点。

则题目变为求1到n+1的最小生成树。

w1 到 wn 就为 1 到 n 与 n+1 的连边。

后面的矩阵就是各自的连边。

代码如下:

#include<bits/stdc++.h>
#define sc(x) scanf("%d",&x)
using namespace std;
int n,ans,cnt=1;
struct edge{
    int from,to,dis;
    bool operator < (const edge &a) const{
        return dis>a.dis;
    }
}e[400<<1];
priority_queue<edge> q;
int fa[400],head[400];
inline int find(int x){
    if(fa[x]==x) return fa[x];
    else return fa[x]=find(fa[x]);
}
int main()
{
    sc(n);
    for(int i=1;i<=n;i++){
        int w;sc(w);
        q.push((edge){i,n+1,w});
        q.push((edge){n+1,i,w});
    }
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        {
            int w;sc(w);
            q.push((edge){i,j,w});
        }
    for(int i=1;i<=n+1;i++) fa[i]=i;
    while(cnt<n+1){
        edge e=q.top();
        q.pop();
        if(find(e.from)==find(e.to)) continue;
        else{
            fa[find(e.from)]=find(e.to);
            cnt++;
            ans+=(e.dis);
        }
    }
    cout<<ans<<endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/ChrisKKK/p/10960386.html