• UVa 908


      题目大意:有n个网站,由m条线路相连,每条线路都有一定的花费,找出连接所有线路的最小花费。

      最小生成树问题(Minimal Spanning Tree, MST),使用Kruskal算法解决。

     1 #include <cstdio>
     2 #include <vector>
     3 #include <algorithm>
     4 using namespace std;
     5 typedef pair<int, int> ii;
     6 #define MAXN 1000100
     7 
     8 int p[MAXN];
     9 
    10 int find(int x)
    11 {
    12     return p[x] == x ? x : p[x] = find(p[x]);
    13 }
    14 
    15 int main()
    16 {
    17 #ifdef LOCAL
    18     freopen("in", "r", stdin);
    19 #endif
    20     int n;
    21     bool first = true;
    22     while (scanf("%d", &n) != EOF)
    23     {
    24         int u, v, w;
    25         int old_cost = 0;
    26         for (int i = 0; i < n-1; i++)
    27         {
    28             scanf("%d%d%d", &u, &v, &w);
    29             old_cost += w;
    30         }
    31         int k;
    32         scanf("%d", &k);
    33         vector< pair<int, ii> > EdgeList;
    34         for (int i = 0; i < k; i++)
    35         {
    36             scanf("%d%d%d", &u, &v, &w);
    37             EdgeList.push_back(make_pair(w, make_pair(u, v)));
    38         }
    39         int m;
    40         scanf("%d", &m);
    41         for (int i = 0; i < m; i++)
    42         {
    43             scanf("%d%d%d", &u, &v, &w);
    44             EdgeList.push_back(make_pair(w, make_pair(u, v)));
    45         }
    46         sort(EdgeList.begin(), EdgeList.end());
    47         for (int i = 1; i <= n; i++)
    48             p[i] = i;
    49         int new_cost = 0;
    50         for (int i = 0; i < EdgeList.size(); i++)
    51         {
    52             w = EdgeList[i].first;
    53             u = EdgeList[i].second.first;
    54             v = EdgeList[i].second.second;
    55             int pu = find(u);
    56             int pv = find(v);
    57             if (pu != pv)
    58             {
    59                 new_cost += w;
    60                 p[pv] = pu;
    61             }
    62         }
    63         if (first)  first = false;
    64         else  printf("
    ");
    65         printf("%d
    %d
    ", old_cost, new_cost);
    66     }
    67     return 0;
    68 }
    View Code
  • 相关阅读:
    java.nio.channels.ClosedChannelException
    JAVA面试题以及基本hadoop
    one
    在远程桌面集群中——配置Python的环境变量
    双系统——在win10系统保存和查看Ubuntu系统中的文件——Linux Reader
    MySQL——安装
    Python--简单读写csv文件
    Python--画图时希腊字母的显示
    IDL——关系运算符Eq Ne Le Lt Gt Ge
    python——利用scipy.stats import pearsonr计算皮尔逊相关系数
  • 原文地址:https://www.cnblogs.com/xiaobaibuhei/p/3327091.html
Copyright © 2020-2023  润新知