题意:
Description
给出一个无向网,求该无向网的最小生成树。各条边的权重不超过100000。
本题与上一题的测试数据是一样的,本题请用Kruskal算法来做,以便与上一题做比较。
Input
输入的第一行是一个整数N,表示该网的顶点个数。 3 ≤ N ≤ 100
接下来是N行,每行N个整数,表示每个顶点到其余顶点的距离。
Output
输出该最小生成树的权重。
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
![大笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct s{
int i,j,k;
friend bool operator < (const s &n,const s & m )
{
return n.k>m.k;
}
}e;
priority_queue<s>q;
int t,a[101];
int h(int i)
{
while(a[i]!=i)
i=a[i];
return a[i];
}
void Q(int n)
{
int i,k,j,l;
for(i=0;i<n;i++)
a[i]=i;
while(!q.empty()&&k!=n-1)
{
e=q.top();
q.pop();
j=h(e.i);
l=h(e.j);
if(j!=l)
{
a[j]=l;
t+=e.k;
k++;
}
}
}
int main()
{
int n,m,i,j,k;
while(~scanf("%d",&n))
{
while(!q.empty()) q.pop();
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&k);
if(i!=j&&j>i)
{
e.i=i;
e.j=j;
e.k=k;
q.push(e);
}
}
t=0;
Q(n);
printf("%d\n",t);
}
return 0;
}