思路:Kruskal
1 #include<cstdio> 2 #include<utility> 3 #include<algorithm> 4 #define w first 5 #define a second.first 6 #define b second.second 7 const int N=5001; 8 typedef std::pair<int,std::pair<int,int> > Edge; 9 class UnionFindSet { 10 private: 11 int anc[N]; 12 public: 13 UnionFindSet(int n) { 14 for(int i=1;i<=n;i++) anc[i]=i; 15 } 16 int Find(int x) { 17 return (x==anc[x])?x:(anc[x]=Find(anc[x])); 18 } 19 void Union(int x,int y) { 20 anc[Find(y)]=Find(x); 21 } 22 }; 23 int main() { 24 int n,m; 25 scanf("%d%d",&n,&m); 26 Edge e[m]; 27 for(int i=0;i<m;i++) scanf("%d%d%d",&e[i].a,&e[i].b,&e[i].w); 28 std::sort(&e[0],&e[m]); 29 UnionFindSet s(n); 30 int ans=0,area=n; 31 for(int i=0;i<m;i++) { 32 if(s.Find(e[i].a)==s.Find(e[i].b)) continue; 33 ans+=e[i].w; 34 s.Union(e[i].a,e[i].b); 35 area--; 36 if(area==1) { 37 printf("%d\n",ans); 38 return 0; 39 } 40 } 41 puts("orz"); 42 return 0; 43 }
时间: 2024-11-13 11:25:50