HDU 3371 Connect the Cities 并查集+Kruskal算法+最小生成树

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3371

代码如下:

注意在杭电提交:G++会超时,可以用C++,可能是sort()函数的问题。

#include<iostream>
#include<stdio.h>
#include<memory.h>
#include<algorithm>
using namespace std;
#define MAX 255003
int father[502];
int n,m,k;

typedef struct Kruskal //存储边的信息
{
	int v1;
	int v2;
	int cost;
};
Kruskal edge[MAX];
bool cmp(const Kruskal &a, const Kruskal &b)
{
	return a.cost<b.cost;
}

/*int unionsearch(int x)//+路径压缩
{
	return x == father[x] ? x : unionsearch(father[x]);
}
*/
int unionsearch(int x)//查找根结点
{
int r=x;
while(father[r]!=r)
    r=father[r];
  return r;
}

int minCost()
{

int sum=0,cnt=0;//记录图的连通分量
for(int i=1;i<=n;i++)
{
 if(father[i]==i)
  cnt++;

}
sort(edge+1,edge+1+m,cmp);//给边排序

for(int i=1;cnt>1&&i<=m;i++)
{
  int fx=unionsearch(edge[i].v1);
  int fy=unionsearch(edge[i].v2);
  if(fx!=fy)
  {
   sum+=edge[i].cost;
   father[fx]=fy;
   cnt--;
  }

}
if(cnt==1) return sum;
 return -1;
}

int main()
{
      int T,i,j;
      scanf("%d",&T);
      while(T--)
      {
        scanf("%d%d%d",&n,&m,&k);
        for(i=1;i<=n;i++)//并查集的初始化
        {
          father[i]=i;
        }
        for(i=1;i<=m;i++)
        {
          scanf("%d%d%d",&edge[i].v1,&edge[i].v2,&edge[i].cost);
        }

        for(i=1;i<=k;i++)
        {
             int t;
             scanf("%d",&t);
             int f,s;
             scanf("%d",&f);
             for(j=1;j<t;j++)
             {
              scanf("%d",&s);
              father[unionsearch(s)]=father[unionsearch(f)];//保证联通支里只有一个祖先
              f=s;
             }
         }
        int ans=minCost();
        printf("%d\n",ans);
      }
	 return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值