ZOJ-1406

经典纯最小生成树,用kruskal解的,感觉比Prim好写,可以做为以后Kruskal算法模板了

#include<stdio.h>
#include<stdlib.h>

struct Village
{
	char name;
	struct Village *parent;
	int rank;
};

struct Road
{
	struct Village *u;
	struct Village *v;
	int cost;
};

static struct Village *make_set(char c)
{
	struct Village *v = malloc(sizeof(struct Village));
	v->name = c;
	v->parent = v;
	v->rank = 0;
	return v;
}

static struct Village *find_set(struct Village *v)
{
	if (v->parent != v)
		v->parent = find_set(v->parent);
	return v->parent;
}

void link(struct Village *u, struct Village *v)
{
	if (u->rank > v->rank)
		v->parent = u;
	else
	{
		u->parent = v;
		if (u->rank == v->rank)
			v->rank++;
	}
}

void union_set(struct Village *u, struct Village *v)
{
	link(find_set(u), find_set(v));
}

static int cmp(const void *p1, const void *p2)
{
	struct Road *r1 = (struct Road*) p1;
	struct Road *r2 = (struct Road*) p2;
	return r1->cost - r2->cost;
}

int main()
{
	int n;
	while (scanf("%d", &n), n)
	{
		getchar();
		struct Village **array = malloc(n * sizeof(struct Village *));
		struct Road *roads = malloc(75 * sizeof(struct Road));
		int i, j, m, cost, index = 0;
		char s[2], t[2];
		for (i = 0; i < n; i++)
			array[i] = make_set('A' + i);
		for (i = 0; i < n - 1; i++)
		{
			scanf("%s %d", s, &m);
			for (j = 0; j < m; j++)
			{
				scanf("%s %d", t, &cost);
				roads[index].u = array[s[0] - 'A'];
				roads[index].v = array[t[0] - 'A'];
				roads[index].cost = cost;
				index++;
			}
			getchar();
		}
		qsort(roads, index, sizeof(struct Road), cmp);
		int sum = 0;
		for (i = 0; i < index; i++)
			if (find_set(roads[i].u) != find_set(roads[i].v))
			{
				union_set(roads[i].u, roads[i].v);
				sum += roads[i].cost;
			}
		printf("%d\n", sum);
		free(roads);
		free(array);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值