zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    文件的增删改查
    集合的使用
    字典的使用
    字符串常用操作
    简单购物车程序练习题
    列表
    数据运算数据类型与
    模块初识
    数据库时间设置
    ubuntu 修改时区
  • 原文地址:https://www.cnblogs.com/ChrisKKK/p/10960386.html
Copyright © 2011-2022 走看看