POJ 2377 Bad Cowtractors( 最小生成树转化 )


**链接:****传送门 **

题意:给 n 个点 , m 个关系,求这些关系的最大生成树,如果无法形成树,则输出 -1

思路:输入时将边权转化为负值就可以将此问题转化为最小生成树的问题了


/*************************************************************************
    > File Name: poj2377.cpp
    > Author:    WArobot 
    > Blog:      http://www.cnblogs.com/WArobot/ 
    > Created Time: 2017年06月19日 星期一 18时38分35秒
 ************************************************************************/

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

const int MAX_N = 1010;
const int MAX_M = 20010;
struct edge{
	int from , to ,cost;
}E[MAX_M];

int n , m;
int par[MAX_N];

void init_union_find_set()	{ for(int i = 0 ; i < MAX_N ; i++) par[i] = i; }
int  find(int x)			{ return x == par[x] ? x : par[x] = find(par[x]); }
bool same(int x,int y)		{ return find(x) == find(y); }
void union_set(int x,int y) { x = find(x); y = find(y);	if(x!=y) par[y] = x; }

bool cmp(edge a,edge b){
	return a.cost < b.cost;
}

int Kruskal(){
	init_union_find_set();
	sort(E,E+m,cmp);
	int ret = 0;
	for(int i = 0 ; i < m ; i++){
		if( !same(E[i].from , E[i].to)){
			union_set(E[i].from,E[i].to);
			ret += E[i].cost;
		}
	}
	int cnt = 0;
	for(int i = 1 ; i <= n ; i++){	if( par[i] == i )	cnt++;   }
	if( cnt > 1 )	ret = 1;
	return ret;
}
int main(){
	int from , to , cost;
	while(~scanf("%d%d",&n,&m)){
		for(int i = 0 ; i < m ; i++){
			scanf("%d%d%d",&from,&to,&cost);
			E[i].from = from , E[i].to = to , E[i].cost = -cost;
		}
		int ret = Kruskal();
		printf("%d\n",-ret);
	}
	return 0;
}
posted @ 2017-06-19 18:51  ojnQ  阅读(172)  评论(0编辑  收藏  举报