zoukankan      html  css  js  c++  java
  • 51 Nod 1640 天气晴朗的魔法( Kruskall )

     1 #include <bits/stdc++.h>
     2 typedef long long LL;
     3 using namespace std;
     4 const int maxn = 2e5+5;
     5 
     6 struct node{
     7     LL u,v,w;
     8     node(){}
     9     node(LL a,LL b,LL c):u(a),v(b),w(c){}
    10 };
    11 
    12 LL f[maxn];
    13 LL n,m;
    14 vector<node>edge;
    15 int Find(LL x)
    16 {
    17     if (f[x] != x)
    18         f[x] = Find(f[x]);
    19     return f[x];
    20 }
    21 
    22 void Union(LL a, LL b)
    23 {
    24     int a1 = Find(a);
    25     int b1 = Find(b);
    26     if (a1 != b1)
    27         f[a1] = b1;
    28 }
    29 bool cmp1(node a,node b)
    30 {
    31     return a.w>b.w;
    32 }
    33 bool cmp2(node a,node b)
    34 {
    35     return a.w<b.w;
    36 }
    37 int main()
    38 {
    39     ios::sync_with_stdio(false);
    40     cin>>n>>m;
    41     for(int i=1;i<=n;i++)
    42         f[i]=i;
    43     for(int i=0;i<m;i++){
    44         LL a,b,c;
    45         cin>>a>>b>>c;
    46         edge.push_back(node(a,b,c));
    47     }
    48     sort(edge.begin(),edge.end(),cmp2);
    49     LL k=0,max_num=-1;
    50     for(int i=0;i<m;i++)
    51     {
    52         if(Find(edge[i].u)!=Find(edge[i].v))
    53         {
    54             Union(edge[i].u,edge[i].v);
    55             max_num = max(max_num,edge[i].w);
    56             k++;
    57         }
    58         if(k==(n-1))
    59             break;
    60     }
    61     sort(edge.begin(),edge.end(),cmp1);
    62     for(int i=1;i<=m;i++)
    63         f[i]=i;
    64     LL ans=0;
    65     k=0;
    66     for(int i=0;i<m;i++)
    67     {
    68         if(edge[i].w>max_num)continue;
    69         if(Find(edge[i].u)!=Find(edge[i].v))
    70         {
    71             Union(edge[i].u,edge[i].v);
    72             ans += edge[i].w;
    73             k++;
    74         }
    75         if(k==(n-1))
    76             break;
    77     }
    78     cout<<ans<<endl;
    79     return 0;
    80 }
  • 相关阅读:
    CentOS7上安装FTP服务
    CentOS7上安装Nginx、PHP、MySQL
    iOS-高性能编程之多线程
    Autoloader什么鬼
    PHP调用外部命令
    PHP使用Redis【重要】
    Windows系统上Redis的安装
    利用nginx与ffmpeg搭建流媒体服务器
    Ubuntu14.04上安装Composer
    find the most comfortable road(并差集,找差值最小的权值)
  • 原文地址:https://www.cnblogs.com/ouyang_wsgwz/p/9580652.html
Copyright © 2011-2022 走看看