时间限制: 1000 ms 空间限制: 131072 KB 具体限制
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n,m,ans,ans1,fa[20001],flag; 4 struct cow{ 5 int father,son,cost; 6 }tree[20001]; 7 bool cmp(cow x,cow y) 8 { 9 return x.cost>y.cost; 10 } 11 int find(int x) 12 { 13 if(fa[x]==x) 14 return x; 15 else 16 return fa[x]=find(fa[x]); 17 } 18 void add(int x,int y) 19 { 20 fa[fa[x]]=fa[y]; 21 } 22 int main() 23 { 24 cin>>n>>m; 25 for(int i=1;i<=n;i++) 26 fa[i]=i; 27 for(int i=1;i<=m;i++) 28 { 29 cin>>tree[i].father>>tree[i].son>>tree[i].cost; 30 } 31 sort(tree+1,tree+1+m,cmp); 32 for(int i=1;i<=m;i++) 33 { 34 if(find(tree[i].father)!=find(tree[i].son)) 35 { 36 ans1++; 37 add(tree[i].father,tree[i].son); 38 ans+=tree[i].cost; 39 } 40 } 41 if(ans1==n-1) 42 { 43 cout<<ans; 44 return 0; 45 } 46 else 47 cout<<-1; 48 return 0; 49 }