PTA_数据结构与算法题目集(中文)_7-10 公路村村通 (30 分)_Kruskal算法

  • 题目地址
  • 题目解析:典型的加权连通图的最小生成树问题
  • 我的代码:
#include<stdio.h>
#include<stdlib.h>

int n, m, bb[1001] = { 0 };
typedef struct road * rp;
struct road{
	int a, b, c;
};
rp aa[3001] = { NULL }; int ai = 0;

void swap(int x, int y){
	rp cap = aa[x];
	aa[x] = aa[y], aa[y] = cap;
}
int  find(int x) {
	while (bb[x]) x = bb[x];
	return x;
}
void buildTree(int a, int b, int c);
rp   useTree(void);
void reBuild(int z);

void reader(void)
{
	scanf("%d %d", &n, &m);
	for (int i = 0, a, b, c; i < m; i++)
	{
		scanf("%d %d %d", &a, &b, &c);
		buildTree(a, b, c);
	}
}

int main()
{
	reader();
	
	rp up = NULL;
	int cost = 0, edge = 0, a, b, c;
	while (true)
	{
		if (!(up = useTree())) break;
		a = up->a, b = up->b, c = up->c;
		a = find(a), b = find(b);
		if (a != b)
			cost += c, edge++, bb[a] = b;
	}
	if (edge == n - 1)
		printf("%d", cost);
	else
		printf("%d", -1);

	return 0;
}
void buildTree(int a, int b, int c)
{
	rp tp = (rp)malloc(sizeof(struct road));
	tp->a = a, tp->b = b, tp->c = c;
	aa[++ai] = tp;

	int ti = ai;
	while (ti/2 > 0 && aa[ti/2]->c > aa[ti]->c)
		swap(ti, ti / 2),ti /= 2;
}
rp   useTree(void)
{
	if (!ai) return NULL;
	rp minP = aa[1];
	aa[1] = aa[ai--];
	reBuild(1);

	return minP;
}
void reBuild(int z)
{
	int y = 2 * z, x = 2 * z + 1;
	if (x <= ai && aa[x]->c < aa[y]->c && aa[x]->c < aa[z]->c)
		swap(x, z), reBuild(x);
	else if (y <= ai && aa[y]->c < aa[z]->c)
		swap(y, z), reBuild(y);
	return;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值