zoukankan      html  css  js  c++  java
  • [洛谷3366]【模板】最小生成树

    思路: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
    ",ans);
    38             return 0;
    39         }
    40     }
    41     puts("orz");
    42     return 0;
    43 }
  • 相关阅读:
    爬虫入门(五)
    爬虫入门(四)
    爬虫入门(三)
    爬虫入门(二)
    爬虫入门(一)
    openpyxl的简单使用
    ansible(三)
    ansible(二)
    ansible(一)
    CF Global Round 10-F
  • 原文地址:https://www.cnblogs.com/skylee03/p/6940589.html
Copyright © 2011-2022 走看看