http://hihocoder.com/problemset/problem/1098
#1098 : 最小生成树二·Kruscal算法
描述
随着小Hi拥有城市数目的增加,在之间所使用的Prim算法已经无法继续使用了——但是幸运的是,经过计算机的分析,小Hi已经筛选出了一些比较适合建造道路的路线,这个数量并没有特别的大。
所以问题变成了——小Hi现在手上拥有N座城市,且已知其中一些城市间建造道路的费用,小Hi希望知道,最少花费多少就可以使得任意两座城市都可以通过所建造的道路互相到达(假设有A、B、C三座城市,只需要在AB之间和BC之间建造道路,那么AC之间也是可以通过这两条道路连通的)。
提示:积累的好处在于可以可以随时从自己的知识库中提取想要的!
输入
每个测试点(输入文件)有且仅有一组测试数据。
在一组测试数据中:
第1行为2个整数N、M,表示小Hi拥有的城市数量和小Hi筛选出路线的条数。
接下来的M行,每行描述一条路线,其中第i行为3个整数N1_i, N2_i, V_i,分别表示这条路线的两个端点和在这条路线上建造道路的费用。
对于100%的数据,满足N<=10^5, M<=10^6,于任意i满足1<=N1_i, N2_i<=N, N1_i≠N2_i, 1<=V_i<=10^3.
对于100%的数据,满足一定存在一种方案,使得任意两座城市都可以互相到达。
输出
对于每组测试数据,输出1个整数Ans,表示为了使任意两座城市都可以通过所建造的道路互相到达至少需要的建造费用。
样例输入
5 29
1 2 674
2 3 249
3 4 672
4 5 933
1 2 788
3 4 147
2 4 504
3 4 38
1 3 65
3 5 6
1 5 865
1 3 590
1 4 682
2 4 227
2 4 636
1 4 312
1 3 143
2 5 158
2 3 516
3 5 102
1 5 605
1 4 99
4 5 224
2 4 198
3 5 894
1 5 845
3 4 7
2 4 14
1 4 185
样例输出
92
思路
题目大意:给你一张无向带权图,求最小生成树
题目思路:采用kruskal算法做。按照边权对所有的m条边按照从小到大排序。每次找到当前边权最小的边,考察期两个端点,是否可以合并为一个集合(用并查集判断),如若可以则这条边加入生成树中。
时间复杂度&&空间复杂度:O(MlogM + M * Ackermann’(M)))&&O(max(m,n))(n为点的个数,m为边的个数)
AC Code
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int nmax=1e6+10;
struct Edge{
int from,to,val;
}edge[nmax];
bool cmp(Edge a,Edge b){//按照边权从小到大排序
return a.val<b.val;
}
int father[nmax];
int findFather(int u){
if(u==father[u]) return u;
else{
int f=findFather(father[u]);
father[u]=f;
return f;
}
}
void Union(int u,int v){
int fu=findFather(u);
int fv=findFather(v);
//if(fu!=fv){
father[u]=v;
//}
}
void init(int n){
for(int i=1;i<=n;i++){
father[i]=i;
}
}
int main(int argc, char** argv) {
int n,m;
while(scanf("%d %d",&n,&m)!=EOF){
init(n);
for(int i=1;i<=m;i++){//1~m
scanf("%d %d %d",&edge[i].from,&edge[i].to,&edge[i].val);
}
sort(edge+1,edge+1+m,cmp);//从小到大排序,每次操作最小的
int ans=0;//边权和
for(int i=1;i<=m;i++){//遍历这m条边,是否能合并到集合S中
int fu=findFather(edge[i].from);
int fv=findFather(edge[i].to);
if(fu!=fv){
Union(fu,fv);
ans+=edge[i].val;
//printf("%d\n",ans);
}
}
printf("%d\n",ans);
}
return 0;
}