克鲁斯卡尔Kruskal

寻找直接或间接连通所有城市的,最小费用的道路集合的问题,就是寻找最小生成树的问题.

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX 100
 
/* 定义边(x,y),权为w */
typedef struct
{
	int x, y;
	int w;
}edge;
 
edge e[MAX];
/* rank[x]表示x的秩 */
int rank[MAX];
/* father[x]表示x的父节点 */
int father[MAX];
int sum;
 //typedef int (*cmptr)(const int a, const int b);
int cmp(const void*a,const void*b)
{
	return (*(edge*)a).w>(*(edge*)b).w?1:-1;
}
/*堆排序*/


/* 初始化集合 */
void Make_Set(int x)
{
	father[x] = x;
	rank[x] = 0;
}
 
/* 查找x元素所在的集合,回溯时压缩路径 */
int Find_Set(int x)
{
	if (x != father[x])
	{
		father[x] = Find_Set(father[x]);
	}
	return father[x];
}
 
/* 合并x,y所在的集合 */
void Union(int x, int y, int w)
{
 
	if (x == y) return;
	/* 将秩较小的树连接到秩较大的树后 */
	if (rank[x] > rank[y])
	{
		father[y] = x;
	}
	else
	{
		if (rank[x] == rank[y])
		{
			rank[y]++;
		}
		father[x] = y;
	}
	sum += w;
}
 
/* 主函数 */
int main()
{

int i, n;
	int x, y;
	char chx, chy;
 	for(i=1;i<=26;i++)
 	Make_Set(i);

	scanf("%d", &n);
	getchar();
 

	for (i = 1; i <=n; i++)
	{
		scanf("%c%c", &chx, &chy);
		getchar();
		scanf("%d",&e[i].w);
		getchar();
		e[i].x = chx - 'a'+1;
		e[i].y = chy - 'a'+1;
	}
 

	qsort(e,n,sizeof(e[0]),cmp);
	sum = 0;
 
	for (i = 1; i <=n; i++)
	{
		x = Find_Set(e[i].x);
		y = Find_Set(e[i].y);
		if (x != y)
		{
			printf("%c - %c : %d\n",e[i].x + 'a'-1, e[i].y + 'a'-1, e[i].w);
			Union(x, y, e[i].w);
		}
	}
	printf("Total:%d\n", sum);
	return 0;	
}      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值