1083. Networking(并查集求最小生成树)

/*1083. Networking(并查集求最小生成树)
*/
#include <iostream>
#include <stdlib.h>
#include <memory.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
#define N 51

struct Edge
{
   int x, y, length;       
}edge[10000];

int n, r, eNum;
int matrix[N][N];
int visit[N][N];

int father[1000];

bool cmp(Edge a , Edge b)
{
  return a.length < b.length;     
}

int get_root(int x)
{
    if(father[x] < 0)
      return x;
    else
      return father[x] = get_root(father[x]); //路径压缩
      /*如   father   -1  1   2   3   4
                i     1   2   3   4   5
            路径压缩后
             father   -1  1   1   1   1    //属于同一根的father都写成等成顶层根id 
                i     1   2   3   4   5
      */ 
}

bool query(int x, int y)
{
     x = get_root(x);
     y = get_root(y);
     return x == y;
}

void union_set(int x, int y)
{
   x = get_root(x);
   y = get_root(y);
   if(x !=y )
     father[x] = y;
     
}

int Kruskal()
{
   int sumLength = 0;
   sort(edge, edge+eNum, cmp);
   fill(father, father+1000, -1);
   for(int i=0; i< eNum; i++)
   {
      if(!query(edge[i].x,edge[i].y))
      {
          sumLength += edge[i].length; 
          union_set(edge[i].x,edge[i].y);                  
      }        
   }  
   
   return sumLength; 
    
}

int main()
{
    int start,end, length;
    while(cin >> n && n !=0)
    {
        cin >> r;
        memset(matrix, 0, sizeof(matrix));
        memset(visit, 0, sizeof(visit));
        eNum = 0;
        for(int i=1; i<=r; i++)
        {
             cin >> start >> end >> length;   
             if(!visit[start][end])
             {
                matrix[start][end] = length;
                matrix[end][start] = length;
                visit[start][end] = 1;
                visit[end][start] = 1;               
             }
             else
             { 
                 //维持两点之间最短的路径即可       
                 if(matrix[start][end] > length)
                    matrix[start][end] = matrix[end][start] = length; 
             }
        }
        for(int i=1; i<=n; i++)
        {
            for(int k=1; k<=i; k++)
            {
               if(matrix[i][k] != 0)  
               {
                   edge[eNum].x =i;
                   edge[eNum].y= k;
                   edge[eNum].length= matrix[i][k]; 
                   eNum++;               
               }
            }    
        }
        
        cout << Kruskal() << endl;  
    }
    system("pause");
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值