首页 > 代码库 > kruskal算法

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算法