最小生成树模板题
跑一次kruskal就可以了
1 /* *********************************************** 2 Author :Sun Yuefeng 3 Created Time :2016/11/9 18:26:37 4 File Name :tree.cpp 5 ************************************************ */ 6 7 #include<cstdio> 8 #include<iostream> 9 #include<algorithm> 10 #include<cmath> 11 #include<cstring> 12 #include<string> 13 #include<bitset> 14 #include<map> 15 #include<set> 16 #include<stack> 17 #include<vector> 18 #include<queue> 19 #include<list> 20 #define M(a,b) memset(a,b,sizeof(a)) 21 using namespace std; 22 typedef long long ll; 23 const int inf=0x3f3f3f3f; 24 const int maxn=55; 25 const int maxm=105; 26 const int mod=1e7+7; 27 int dx[8]= {0,0,1,-1,1,-1,1,-1}; 28 int dy[8]= {1,-1,0,0,-1,1,1,-1}; 29 30 int f[maxn],tol,n,m; 31 32 struct _edge 33 { 34 int u,v,w; 35 }edge[maxm]; 36 37 bool cmp(_edge a,_edge b) 38 { 39 return a.w<b.w; 40 } 41 42 void addedge(int u,int v,int w) 43 { 44 edge[tol].u=u; 45 edge[tol].v=v; 46 edge[tol].w=w; 47 tol++; 48 } 49 50 int _find(int x) 51 { 52 if(f[x]==-1) return x; 53 else return f[x]=_find(f[x]); 54 } 55 56 int kruskal() 57 { 58 M(f,-1); 59 sort(edge,edge+tol,cmp); 60 int cnt=0,ans=0; 61 int u,v,w,f1,f2; 62 for(int i=0;i<tol;i++) 63 { 64 u=edge[i].u; 65 v=edge[i].v; 66 w=edge[i].w; 67 f1=_find(u); 68 f2=_find(v); 69 if(f1!=f2) 70 { 71 ans+=w; 72 f[f1]=f2; 73 cnt++; 74 } 75 if(cnt==n-1) break; 76 } 77 return ans; 78 } 79 80 int main() 81 { 82 //freopen("in.txt","r",stdin); 83 //freopen("out.txt","w",stdout); 84 while(~scanf("%d%d",&n,&m)&&n) 85 { 86 tol=0; 87 for(int i=0;i<m;i++) 88 { 89 int u,v,w; 90 scanf("%d%d%d",&u,&v,&w); 91 addedge(u,v,w); 92 } 93 printf("%d ",kruskal()); 94 } 95 return 0; 96 }