几何 + 思路构造 + 高斯消元 Destroy Walls HDU - 6187

本文介绍了一种使用C++实现的最小生成树算法,通过Kruskal算法来找到加权图中的最小生成树。该程序定义了边的结构并实现了并查集数据结构来高效地合并节点集合,同时避免形成环路。
#include <stdio.h>
#include <vector>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
#define LL long long

const int MAXV=100000+3;
const int MAXE=200000+3;

struct Edge
{
    int from, to, cost;
    Edge(int f=0, int t=0, int c=0):from(f), to(t), cost(c){}
    bool operator < (const Edge &other)const
    {
        return cost>other.cost;
    }
}edge[MAXE];

int V, E;
int par[MAXV], high[MAXV];

int findfather(int x)
{
    return par[x]=par[x]==x?x:findfather(par[x]);
}

bool unite(int a, int b)
{
    int fa=findfather(a), fb=findfather(b);
    if(fa==fb)
        return false;
    if(high[fa]>high[fb])
        par[fa]=fb;
    else
    {
        par[fb]=fa;
        if(high[fa]==high[fb])
            ++high[fb];
    }
    return true;
}

void init()//初始化
{
    for(int i=0;i<=V;++i)
    {
        par[i]=i;
        high[i]=0;
    }
}

int main()
{
    while(~scanf("%d%d", &V, &E))
    {
        init();
        for(int i=0;i<V;++i)
        {
            int x, y;
            scanf("%d%d", &x, &y);
        }
        LL ans=0;
        for(int i=0;i<E;++i)
        {
            scanf("%d%d%d", &edge[i].from, &edge[i].to, &edge[i].cost);
            ans+=edge[i].cost;
        }
        sort(edge, edge+E);
        int cnt=0;//保留的边数
        for(int i=0;i<E;++i)
            if(unite(edge[i].from, edge[i].to))
            {
                ans-=edge[i].cost;
                ++cnt;
            }
        printf("%d %lld\n", E-cnt, ans);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值