zoukankan      html  css  js  c++  java
  • 修复公路 洛谷1111 并查集 水题

      首先将所有边按照修复时间进行排序,然后逐条边进行加入,当已联通时break并输出当前time值,否则输出-1

     1 #include <cstdio>
     2 #include <cstring>
     3 #include <algorithm>
     4 
     5 const int maxn = 1000 + 500;
     6 const int maxm = 100000 + 500;
     7 
     8 struct data{
     9     int from;
    10     int to;
    11     int tm;
    12 };
    13 int father[maxn];
    14 int cur;
    15 data p[maxm];
    16 int n, m;
    17 
    18 bool cmp(data aa, data bb) {
    19     return aa.tm < bb.tm;
    20 }
    21 int getfather(int x) {
    22     if (father[x] == x) return (x);
    23     return (father[x] = getfather(father[x]));
    24 }
    25 
    26 int main () {
    27     scanf("%d %d", &n, &m);
    28     cur = n;
    29     for (int i = 1; i <= n; i++) father[i] = i;
    30     for (int i = 1; i <= m; i++) {
    31         scanf("%d %d %d", &p[i].from, &p[i].to, &p[i].tm);
    32     }
    33     std :: sort(p + 1, p + m + 1, cmp);
    34     int j;
    35     for (j = 1; j <= m; j++) {
    36         int tx = getfather(p[j].from);
    37         int ty = getfather(p[j].to);
    38         if (tx == ty) continue;
    39         father[tx] = ty;
    40         cur--;
    41         if (cur == 1) break;
    42     }
    43     if (cur == 1) printf("%d", p[j].tm);
    44     else printf("-1");
    45     return 0;
    46 }
  • 相关阅读:
    [每日一题]石子合并 -- 区间DP
    [每日一题]: 最长上升子序列 AND 最长不上升子序列
    [每日一题]:最大子矩阵和
    入门DP--最大子段和
    [转载]:正确的提问方式
    springmvc.xml
    service层springservice.xml文件
    aop切面配置
    配置事务通知
    短信验证
  • 原文地址:https://www.cnblogs.com/CtsNevermore/p/5990776.html
Copyright © 2011-2022 走看看