zoukankan      html  css  js  c++  java
  • POJ-2421-Constructing Roads

    链接:https://vjudge.net/problem/POJ-2421#author=tsacm123

    题意:

    有N个村庄,从1到N,你应该修建一些道路,这样每两个村庄就可以连接起来。我们说两个村庄A和B相连,当且仅当A和B之间有一条路,或者存在一个村庄C使得A和C之间有一条路,并且C和B相连。我们知道一些村庄之间已经有一些道路了,你的工作是修建一些道路,这样所有的村庄都连接起来,所有道路的长度都是最小的。

    思路:

    最小生成树

    代码:

    #include <iostream>
    #include <memory.h>
    #include <string>
    #include <istream>
    #include <sstream>
    #include <vector>
    #include <stack>
    #include <algorithm>
    #include <map>
    #include <queue>
    #include <math.h>
    using namespace std;
    typedef long long LL;
    const int MAXM = 20000+10;
    const int MAXN = 100+10;
    
    struct Path
    {
        int _l,_r;
        double _value;
        bool operator < (const Path & that)const{
            return this->_value < that._value;
        }
    }path[MAXM];
    
    int Father[MAXN];
    
    int Get_F(int x)
    {
        return Father[x] = (Father[x] == x) ? x : Get_F(Father[x]);
    }
    
    int main()
    {
        int n, q;
        cin >> n;
        int pos = 0;
        int len;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
            {
                cin >> len;
                if (i != j)
                {
                    path[++pos]._l = i;
                    path[pos]._r = j;
                    path[pos]._value = len;
                }
            }
        cin >> q;
        int l,r;
        for (int i = 1;i <= q;i++)
        {
            cin >> l >> r;
            path[++pos]._l = l;
            path[pos]._r = r;
            path[pos]._value = 0;
        }
        for (int i = 1; i <= n; i++)
            Father[i] = i;
        sort(path + 1, path + 1 + pos);
        int sum = 0;
        for (int i = 1; i <= pos; i++)
        {
            int tl = Get_F(path[i]._l);
            int tr = Get_F(path[i]._r);
            if (tl != tr)
            {
                Father[tl] = tr;
                sum += path[i]._value;
            }
        }
        cout << sum << endl;
    
    
        return 0;
    }
    

      

  • 相关阅读:
    ES8 Async 和 Await
    js中字节B转化成KB,MB,GB
    理解与使用JavaScript中的回调函数
    JavaScript与函数式编程
    Deno 意味着什么?
    call、apply、bind
    测量JavaScript函数的性能的简单方法及与其他方式对比
    promise
    SQL游标原理和使用方法
    SQL循环语句
  • 原文地址:https://www.cnblogs.com/YDDDD/p/10330962.html
Copyright © 2011-2022 走看看