九度教程第73题

本文使用C语言实现了一种解决最小生成树问题的方法,通过读取输入数据,构建边集并进行排序,利用并查集算法找到最小生成树,并输出其权重之和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:http://jobdu.sinaapp.com/problem.php?cid=1040&pid=72

C语言源码:

#include<stdio.h>
#include<stdlib.h>
#define maxsize 1000
typedef struct edge
{
	int a,b;
	int weight;
}edge;
edge E[maxsize];
int T[27];
int findroot(int x)
{
	int temp;
	if(T[x]==-1)
		return x;
	else
	{
		temp=findroot(T[x]);
		T[x]=temp;
		return temp;
	}
}
int cmp(const void *a,const void *b)
{
	struct edge *aa=(edge *)a;
	struct edge *bb=(edge *)b;
	return aa->weight-bb->weight;
}
int main()
{
	int n,weight,k,i,j,top,roota,rootb,min;
	char point1,point2;
	scanf("%d",&n);
	getchar();
	while(n)
	{
		top=0;
		for(i=0;i<n-1;i++)
		{
			point1=getchar();
			scanf("%d",&k);
			getchar();
			while(k--)
			{
				point2=getchar();
				getchar();
				scanf("%d",&weight);
				getchar();
				E[top].a=point1-'A';
				E[top].b=point2-'A';
				E[top++].weight=weight;
			}

		}
		qsort(E,top,sizeof(E[0]),cmp);
		for(i=0;i<n;i++)
			T[i]=-1;
		min=0;
		for(i=0;i<top;i++)
		{
			roota=findroot(E[i].a);
			rootb=findroot(E[i].b);
			if(roota!=rootb)
			{
				T[rootb]=roota;
				min+=E[i].weight;
			}
		}
		printf("%d\n",min);
		scanf("%d",&n);
		getchar();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值