前言:
先介绍一下最小生成树。对于n个结点,用n-1条边使它们相联通,形成一棵树,这个树就叫生成树,其中所有边权值和最小的生成树就是最小生成树。
其次,介绍一下kruskal算法的思想。1.讲所有边按升序排序,2,选择权值最小的边。如果边的两个结点不在一个连通分量里,就把一个结点的根节点作为另一个结点的根节点的子节点;反之,在同一个连通分量中,忽略掉。3.重复第二步直到所有顶点都在一个连通分量中。
这里,连通分量的判定和结点之间的合并用到了并查集。
问题:
还是畅通工程。
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度。
Sample Input
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
Sample Output
3
5
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<string>
using namespace std;
const int maxn=100;
int n,sum;
int root[maxn];
struct Edge{
int l,r,cost;
bool operator < (const Edge &A) const{//ÖØÔØÔËËã·û£¬±ãÓÚÅÅÐò¡£
return cost<A.cost;
}
};
int findRoot(int x)
{
while(x!=root[x])
{
root[x]=root[root[x]];
x=root[x];
}
return x;
}
int unionRoot(Edge e)
{
int xx=findRoot(e.l);
int yy=findRoot(e.r);
if(xx!=yy)
{
root[yy]=xx;
sum+=e.cost;
}
}
int main()
{
while(cin>>n&&n!=0)
{
Edge edge[5000];
for(int i=0;i<n*(n-1)/2;i++)
cin>>edge[i].l>>edge[i].r>>edge[i].cost;
sort(edge,edge+n*(n-1)/2);
sum=0;
for(int i=1;i<=n;i++)
root[i]=i;
for(int i=0;i<n*(n-1)/2;i++)
unionRoot(edge[i]);
cout<<sum<<endl;
}
return 0;
}
结果:
总结:
时间复杂度:
O(eloge)
e:总边数。