Kruskal算法

克魯斯卡爾(Kruskal)算法(只與邊相關)


算法描述:克魯斯卡爾算法需要對圖的邊進行訪問,所以克魯斯卡爾算法的時間複雜度只和邊又關係,可以證明其時間複雜度爲O(eloge)。

算法過程:

1.將圖各邊按照權值進行排序

2.將圖遍歷一次,找出權值最小的邊,(條件:此次找出的邊不能和已加入最小生成樹集合的邊構成環),若符合條件,則加入最小生成樹的集合中。不符合條件則繼續遍歷圖,尋找下一個最小權值的邊。

3.遞歸重複步驟1,直到找出n-1條邊爲止(設圖有n個結點,則最小生成樹的邊數應爲n-1條),算法結束。得到的就是此圖的最小生成樹。


克魯斯卡爾(Kruskal)算法因爲只與邊相關,則適合求稀疏圖的最小生成樹。而prime算法因爲只與頂點有關,所以適合求稠密圖的最小生成樹。


代碼如下:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;
#define MAX 1000
int father[MAX], son[MAX];
int v, l;

typedef struct Kruskal //存儲邊的信息
{
	int a;
	int b;
	int value;
};

bool cmp(const Kruskal & a, const Kruskal & b)
{
	return a.value < b.value;
}

int unionsearch(int x) //查找根結點+路徑壓縮
{
	return x == father[x] ? x : unionsearch(father[x]);
}

bool join(int x, int y) //合併
{
	int root1, root2;
	root1 = unionsearch(x);
	root2 = unionsearch(y);
	if(root1 == root2) //爲環
		return false;
	else if(son[root1] >= son[root2])
		{
			father[root2] = root1;
			son[root1] += son[root2];
		}
		else
		{
			father[root1] = root2;
			son[root2] += son[root1];
		}
	return true;
}

int main()
{
	int ncase, ltotal, sum, flag;
	Kruskal edge[MAX];
	scanf("%d", &ncase);
	while(ncase--)
	{
		scanf("%d%d", &v, &l);
		ltotal = 0, sum = 0, flag = 0;
		for(int i = 1; i <= v; ++i) //初始化
		{
			father[i] = i;
			son[i] = 1;
		}
		for(int i = 1; i <= l ; ++i)
		{
			scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].value);
		}
		sort(edge + 1, edge + 1 + l, cmp); //按權值由小到大排序
		for(int i = 1; i <= l; ++i)
		{
			if(join(edge[i].a, edge[i].b))
			{
				ltotal++; //邊數加1
				sum += edge[i].value; //記錄權值之和
				cout<<edge[i].a<<"->"<<edge[i].b<<endl;
			}
			if(ltotal == v - 1) //最小生成樹條件:邊數=頂點數-1
			{
				flag = 1;
				break;
			}
		}
		if(flag) printf("%d\n", sum);
		else printf("data error.\n");
	}
	return 0;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章