c++最小生成树之krustal算法




//最小生成树之krustal算法
#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;
#define MAX_LINE 7


char tree[MAX_LINE][MAX_LINE]
={
	{-1, 7, -1, 5, -1, -1, -1},
	{7, -1,  8, 9,  7, -1, -1},
	{-1, 8, -1, -1, 5, -1, -1},
	{5,  9, -1, -1, 15, 6, -1},
	{-1, 7,  5, 15, -1, 8, 9},
	{-1,-1, -1,  6,  8,-1, 11},
	{-1,-1, -1, -1,  9,11, -1}
};
typedef struct line
{
	
	char row;
	char col;
	char value;
	friend bool operator< (line n1, line n2)
    {
        return n1.value > n2.value;
    }
} Line;

Line lines[MAX_LINE*MAX_LINE];
char father[MAX_LINE];//store father id
priority_queue<Line> qLines;
char linesIndex = 0;

void krustal();
void init(){
	char i,j;
	Line tmpLine;
	for( i = 0;i<MAX_LINE;i++)
	{
		//Init father
		father[i] = i;
		for(j = i;j<MAX_LINE;j++)
		{
			if(tree[i][j] == -1)
				continue;
			tmpLine.row = i;
			tmpLine.col = j;
			tmpLine.value = tree[i][j];
			qLines.push(tmpLine);
		}
	}
}
char findFather(char son){
	if(father[son] == son)
		return son;
	return father[son] = findFather(father[son]);
}
int main(){
	init();
	cout<<"krustal算法最小生成树"<<endl;
	krustal();
	getchar();
	return 0;
}
void krustal(){
	Line tmpLine;
	char row,col,value;
	char fatherRow,fatherCol;
	char i,sum = 0;

	while(linesIndex<MAX_LINE-1)
	{
		tmpLine = qLines.top();
		qLines.pop();
		row = tmpLine.row;
		col = tmpLine.col;
		value = tmpLine.value;

		fatherRow = findFather(row);
		fatherCol = findFather(col);
		if(fatherRow == fatherCol)//构成环
			continue;
		//加入到lines
		lines[linesIndex++] = tmpLine;

		//更新集合信息
		char tmpCol = col;
		char tmptmp;
		while (tmpCol!=father[tmpCol])
		{
			tmptmp = father[tmpCol];
			father[tmpCol] = fatherRow;
			tmpCol = tmptmp;
		}
		father[tmpCol] = fatherRow;
	}
	//打印结果
	for(i = 0;i<linesIndex;i++){
		printf("<%d,%d>\n",lines[i].row,lines[i].col);
		sum+=lines[i].value;
	}
	printf("total path is %d\n",sum);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值