最大生成树,kruskal将权重取负。如果并查集的大小不等于1,则说明没有将所有的谷仓连接起来,输出-1。

#include <iostream>
#include <algorithm>

using namespace std;

const int MAXN = 1005;
const int MAXM = 20005;

int n, m, a, b, c;
int cost[MAXN][MAXN];

int par[MAXN];
int rank[MAXN];

struct edge {
	int x;
	int y;
	int cost;
}es[MAXN];

bool cmp(const edge& e1, const edge& e2) {
	return e1.cost < e2.cost;
}

void init(int n) {
	for(int i=0; i<n; i++) {
		par[i] = i;
		rank[i] = 0;
	}
}

int find(int x) {
	if(par[x] == x)
		return x;
	else
		return par[x] = find(par[x]);
}

void unite(int x, int y) {
	x = find(x);
	y = find(y);
	if(x == y)	return;
	
	if(rank[x] < rank[y])
		par[x] = y;
	else {
		par[y] = x;
		if(rank[x] == rank[y])	rank[x]++;
	}
}

bool same(int x, int y) {
	return find(x) == find(y);
}

int main() {
	
	scanf("%d%d", &n, &m);
	for(int i=0; i<m; i++) {
		scanf("%d%d%d", &es[i].x, &es[i].y, &es[i].cost);
		es[i].cost = -es[i].cost;		
	}
	sort(es, es+m, cmp);
	init(n);
	int res = 0;
	int trees = n;
	for(int i=0; i<m; i++) {
		edge e = es[i];
		if(!same(e.x, e.y)) {
			unite(e.x, e.y);
			res += e.cost;
			trees--;
		}
	}
	if(trees > 1)
		printf("%d\n", -1);
	else
		printf("%d\n", -res);
	
	return 0;
}


优质内容筛选与推荐>>
1、Flex与.NET互操作(四):使用HttpService、URLReqeust和URLLoader加载/传输数据
2、js日期选择控件
3、arduino 大气气压模块 BOSCH BMP085
4、移动端页面适配解决方案
5、转载:Compressive Sensing: The Big Picture


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号