Bad Cowtractors POJ - 2377

原题传送门

题意:周扒皮让阿凡提修建无线网,要求连接每一个节点,但是不想给钱,阿凡提知道了就准备给扒皮建立一个最大生成树

思路:Kruskal算法建立最大生成树,判断能否连通每个节点,不能输出-1

#include <cstdio>
#include <iostream>
#include <vector>
#include <cmath>
#include <queue>
#include <algorithm>
#include <cstring>
const int maxm = 21000;
const int INF = 1e6;

using namespace std;

struct edge{
	int u, v, cost;
};
bool cmp(edge e1, edge e2){
	return e1.cost > e2.cost;
}

int N, M; 
edge es[maxm];
int par[maxm];
int ran[maxm];

//初始
void Init(int n){
	for(int i = 0; i < n; i++){
		par[i] = i;
		ran[i] = 0;	
	}
	
}
//查询
int Find(int x){
	if(x == par[x])
		return par[x];
	else
		return par[x] = Find(par[x]);
}
//合并
void Unit(int x, int y){
	x = Find(x);
	y = Find(y);
	
	if(x == y)
		return ;
	if(ran[x] > ran[y])
		par[y] = x;
	else{
		par[x] = y;
		if(ran[x] == ran[y])
			ran[y]++;
	}
}
//判断
bool Same(int x, int y){
	return Find(x) == Find(y);
}

void Solve(){
	long long ans = 0;
	Init(N);
	
	//排序,在不产生圈的情况下将最小边入队
	sort(es, es+M, cmp);
	for(int i = 0; i < M; i++)
		if(!Same(es[i].u, es[i].v)){
			Unit(es[i].u, es[i].v);
			ans += es[i].cost;
		}
		
	//判断是否连通 
	for(int i = 2; i <= N; i++)
		if(!Same(1,i)){
			ans = -1;
			break;
		}
	cout << ans << endl;
	return ;
}
//测试函数 
int main(){
	freopen("D:\\钢铁程序员\\程序数据\\075网络.txt", "r", stdin);
	scanf("%d%d", &N, &M);
	for(int i = 0; i < M; i++)
		scanf("%d%d%d", &es[i].u, &es[i].v, &es[i].cost);
	
	Solve();
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值