hdu3371——最小生成数

题意:给n个城市,m条路,k组已知路,求最小费用联通所有城市;

思路:先连已知的,在连没连的;

坑点,两处,已标记在代码中

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
struct node
{
	int x,y,value;
}city[100050];
int root[550];
int times,n,m,k;
bool cmp(node a,node b)
{
	return a.value<b.value;
}
int find_root(int son)
{
	if(son!=root[son])
	{
		root[son]=find_root(root[son]);
	}
	return root[son];
}
int main()
{
	scanf("%d",×);
	while(times--)
	{
		scanf("%d%d%d",&n,&m,&k);
		for(int i=1;i<=n;i++)
		{
			root[i]=i;
		}
		for(int i=1;i<=m;i++)
		{
			scanf("%d%d%d",&city[i].x,&city[i].y,&city[i].value);
		}
		sort(city+1,city+m+1,cmp);
		int fx,fy;int sum=0;int flag=0;
		for(int i=1;i<=k;i++)
		{
			int j;int l;int p;
			scanf("%d",&j);scanf("%d",&l);
			for(int kk=2;kk<=j;kk++)
			{
				scanf("%d",&p);
				fx=find_root(l);//此处如果不判断的话会爆栈, 
				fy=find_root(p);
				if(fx!=fy)
				{
					root[fy]=fx;
				}
			}
		}
		for(int i=1;i<=m;i++)
		{
			fx=find_root(city[i].x);
			fy=find_root(city[i].y);
			if(fx!=fy)
			{
				root[fy]=fx;
				sum+=city[i].value;
			}
		}
		for(int i=1;i<=n;i++)//如果用数组记录根节点有多少子节点会超时 
		{
			if(root[i]==i)
			{
				flag++;
			}
		}
		if(flag==1) printf("%d\n",sum);
		else printf("-1\n");
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值