zoukankan      html  css  js  c++  java
  • POJ

    直接Kruskal

    但是注意一点的是 从起点到终点 

    只要起点和终点连通就可以停止添加路径了 因为再添加 就会减小weight最小的路

     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <string>
     4 #include <string.h>
     5 #include <map>
     6 #include <queue>
     7 #include <fstream>
     8 #include <algorithm>
     9 #include <string.h>
    10 #define READ() freopen("in.txt", "r", stdin);
    11 #define MAXV 1007
    12 #define MAXE 1000007
    13 
    14 using namespace std;
    15 
    16 struct Edge
    17 {
    18     int from, to, cost;
    19     Edge () {}
    20     Edge (int from, int to, int cost) : from(from), to(to), cost(cost) {}
    21 }edge[MAXE];
    22 int num = 0;
    23 void Add(int from, int to, int cost)
    24 {
    25     edge[num++] = Edge(from, to, cost);
    26 }
    27 int par[MAXV];
    28 int find(int x)
    29 {
    30     if (x == par[x]) return x;
    31     else return par[x] = find(par[x]);
    32 }
    33 void unite(int x, int y)
    34 {
    35     int px = find(x), py = find(y);
    36     if (px == py) return ;
    37     else par[py] = px;
    38 }
    39 bool same(int x, int y)
    40 {
    41     int px = find(x), py = find(y);
    42     return px == py;
    43 }
    44 
    45 bool cmp(Edge e1, Edge e2)
    46 {
    47     return e1.cost > e2.cost;
    48 }
    49 
    50 int dist[MAXE];
    51 int n, m;
    52 int Kruskal()
    53 {
    54     int n1 = 0;
    55     sort(edge, edge+num, cmp);
    56     for (int i = 0; i < num; i++)
    57     {
    58         Edge e = edge[i];
    59         if (!same(e.from, e.to))
    60         {
    61             unite(e.from, e.to);
    62             dist[n1++] = e.cost;
    63         }
    64         if (same(1, n)) break;
    65     }
    66     sort(dist, dist+n1);
    67     return dist[0];
    68 }
    69 int main()
    70 {
    71     READ()
    72     int T,cnt = 1;
    73     scanf("%d", &T);
    74     while (T--)
    75     {
    76         scanf("%d%d", &n, &m);
    77         for (int i = 1;i <= n; i++) par[i] = i;
    78         memset(edge, 0, sizeof(edge));
    79         for (int i = 0; i < m; i++)
    80         {
    81             int from, to, cost;
    82             scanf("%d%d%d", &from, &to, &cost);
    83             Add(from, to, cost);
    84             Add(to, from, cost);
    85         }
    86         int ans = Kruskal();
    87         printf("Scenario #%d:
    %d
    
    ", cnt++, ans);
    88     }
    89 }
  • 相关阅读:
    HDU-1702-ACboy needs your help again!(Stack)
    HDU1276-士兵队列训练问题 (Queue)
    HDU1285-确定比赛名次(拓扑+优先队列)
    The Preliminary Contest for ICPC Asia Nanjing 2019
    拓扑排序板子 hihocoder-1174
    BZOJ1066 [SCOI2007]蜥蜴
    BZOJ3888 [Usaco2015 Jan]Stampede
    BZOJ1718 [Usaco2006 Jan] Redundant Paths 分离的路径
    BZOJ1112 [POI2008]砖块Klo
    BZOJ1031 [JSOI2007]字符加密Cipher
  • 原文地址:https://www.cnblogs.com/oscar-cnblogs/p/6435464.html
Copyright © 2011-2022 走看看