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

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

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;
}

 

你可能感兴趣的:(Kruskal算法)