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;
}

  

转载于:https://www.cnblogs.com/YDDDD/p/10330962.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值