码迷,mamicode.com
首页 > 编程语言 > 详细

kruskal算法

时间:2014-12-08 09:21:00      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:kruskal

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

struct edge {
	int begin;
	int end;
	int cost;
};

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

int findSet(int *parent, int i)
{
	int j = i;
	while (parent[j] > 0)
		j = parent[j];
	return j;
}

bool unionSet(int *parent, int i, int j)
{
	int a = findSet(parent,i);
	int b = findSet(parent,j);
	if (a != b) {
		int x = parent[i] + parent[j];
		if (parent[i] > parent[j]) {
			parent[i] = j;
			parent[j] = x;
		}
		else {
			parent[j] = i;
			parent[i] = x;
		}
		return true;
	}
	return false;
}

int main(void)
{
	int mincost = 0;
	struct edge cost[100 * 100];
	int input;
	while (cin >> input) {
		int *parent = new int[input];
		memset(parent, -1, input*sizeof(int));
		int value,index = 0;
		for (int i = 0; i < input; i++)
			for (int j = 0; j < input; j++) {
				cin >> value;
				if (i > j) {
					cost[index].begin = i;
					cost[index].end = j;
					cost[index].cost = value;
					index++;
				}
			}
		sort(cost, cost + index, cmp);
		int num = 0;
		for (int i = 0; i < input; i++) {
			if (unionSet(parent,cost[i].begin, cost[i].end)) {
				mincost += cost[i].cost;
				if (++num == input - 1)
					break;
			}
		}
		printf("%d\n", mincost);
	}

	return 0;
}

kruskal算法

标签:kruskal

原文地址:http://blog.csdn.net/u012637838/article/details/41793299

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!