/*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;
}
1083. Networking(并查集求最小生成树)
最新推荐文章于 2019-03-11 21:29:00 发布