• 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
  • 相关阅读:
    Linux五种IO模型性能分析
    并发容器之CopyOnWriteArrayList(转载)
    Web.XML配置详解
    Servlet,过滤器,监听器,拦截器的区别
    JAVA反射机制详解
    Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue
    Jdk1.6 JUC源码解析(12)-ArrayBlockingQueue
    Jdk1.6 JUC源码解析(6)-locks-AbstractQueuedSynchronizer
    Jdk1.6 JUC源码解析(7)-locks-ReentrantLock
    hibernate 其中七种关联关系
  • 原文地址:https://www.cnblogs.com/xiaobaibuhei/p/3327091.html
Copyright © 2020-2023  润新知