• 题解 P1550 【[USACO08OCT]打井Watering Hole】


    题面(翻译有点问题,最后一句话)

    农民John 决定将水引入到他的n(1<=n<=300)个牧场。他准备通过挖若

    干井,并在各块田中修筑水道来连通各块田地以供水。在第i 号田中挖一口井需要花费W_i(1<=W_i<=100,000)元。连接i 号田与j 号田需要P_ij (1 <= P_ij <= 100,000 , P_ji=P_ij)元。

    请求出农民John 需要为使所有农场都与有水的农场相连或拥有水井所需要的钱数。

    题意

    有n个点,每个点之间都有边权,但是每个点也有点权。

    要求算出每个点都连通的情况下(但是不要求每个点的点权都算上),最小价值。

    题解

    这题很容易想到最小生成树,但是又有好多人不敢下手去写最小生成树,因为这里的每个点还有点权。

    我们可以转换一下思路,把每个点的点权当成一个指向自己的边权,然后构造一棵最小生成树就好了!

    代码

    #include<bits/stdc++.h>
    using namespace std;
    
    const int maxx = 1e3+10;
    int n,cnt = 0,fa[maxx*maxx];
    
    struct edge{
        int u,v,w;
        bool operator < (const edge &qwq)
        {
            return w < qwq.w;
        }
    }G[maxx*maxx];
    
    inline void init()
    {
        cin >> n;
        for(int i = 1;i <= n;++i)
        {
            int w;
            cin >> w;
            G[++cnt].u = 0;
            G[cnt].v = i;
            G[cnt].w = w;
        }
        for(int i = 1;i <= n;++i)
        {
            for(int j = 1;j <= n;++j)
            {
                int w;
                cin >> w;
                if(i > j)
                {
                    G[++cnt].u = i;
                    G[cnt].v = j;
                    G[cnt].w = w;
                }
            }
        }
        for(int i = 1;i <= cnt;++i) fa[i] = i;
    }    
    
    inline int fin(int x)
    {
        return fa[x] == x ? x : fa[x] = fin(fa[x]);
    }
    
    inline int kul()
    {
        sort(G+1,G+cnt+1);
        int ans = 0,qwq = 0;
        
        for(int i = 1;i <= cnt;++i)
        {
            int x = fin(G[i].u),y = fin(G[i].v);
            if(x != y)
            { 
                fa[x] = y;
                ++qwq;
                ans += G[i].w;
            }
            if(qwq == n) break;
        }
    
        return ans;
    }
    
    int main(int argc, char const *argv[])
    {
        init();
        cout << kul();
        return 0;
    }
    
  • 相关阅读:
    Docker 常用命令及操作
    Docker 启动 tomcat 成功,但是访问为 404
    Linux 使用 yum install 安装程序时,提示另外一个程序锁定了 yum 等待它退出...
    Centos 6.8 安装 Docker 及 Docker 入门介绍
    iptables常见的模块拓展-m iprange 、-m multiport、
    iptables -m state模块 注意与-m conntrack的区别
    ros single network adapter的nat
    trap 信号捕捉
    ifconfig命令
    使用pipework给docker配置物理机器网卡上的地址
  • 原文地址:https://www.cnblogs.com/Chicago/p/9920817.html
Copyright © 2020-2023  润新知