- Time: 2016-04-13-23:56:49
- Title Number: [2016-04-13][hdu][1233][or smooth works]
- The main idea: to find the minimum spanning tree
- Analysis: Direct Kruskal
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100 + 10;
int fa[maxn];
struct Edge{
int v c ;
edge ( int _u = 0 int _v = 0 int _c = 0 ): u _u v _v c _c
bool operator < (const Edge & a)const{
return c < a.c;
}
}e[maxn*maxn];
int fnd(int x){
return x == fa[x] ? x: (fa[x] = fnd(fa[x]));
}
void ini(int n){
for(int i = 0 ; i <= n ; ++i){
fa[i] = i;
}
}
int main(){
int n;
//freopen("in.txt","r",stdin);
while(~scanf("%d",&n) && n){
int a,b,c;
ini(n);
for(int i = 0 ; i < n * (n-1)/2;++i){
scanf("%d%d%d",&a,&b,&c);
e[i] = Edge(a,b,c);
}
sort(e,e+n*(n-1)/2);
int cnt = 0,ans = 0;
for ( int i = 0 ; I < n * ( n - 1 )/ 2 ;++ i
int f1 = fnd(e[i].u);
int f2 = fnd(e[i].v);
if(f1 != f2){
fa[f1] = fa[f2];
ans += e[i].c;
++cnt;
}
if(cnt == n - 1) break;
}
printf("%d\n",ans);
}
return 0;
}
From for notes (Wiz)
[2016-04-13] [HDU] [1233] [or Smooth works]