zoukankan      html  css  js  c++  java
  • LeetCode 684. 冗余连接 | 1627. 带阈值的图连通性(并查集)

    LeetCode 684. 冗余连接

     简单并查集, 搞出一棵树即可

     1 class Solution {
     2 public:
     3     int fi(int x, vector<int>& fa) {
     4         return x == fa[x] ? x : fa[x] = fi(fa[x], fa);
     5     }
     6     vector<int> findRedundantConnection(vector<vector<int>>& edges) {
     7         int n = edges.size();
     8         vector<int> ans;
     9         vector<int> fa(n + 1, 0);
    10         for (int i = 0; i <= n; i++) fa[i] = i;
    11         for (auto p : edges) {
    12             int x = fi(p[0], fa), y = fi(p[1], fa);
    13             if (x != y) {
    14                 fa[x] = y;
    15             } else {
    16                 ans = p;
    17                 break;
    18             }
    19         }
    20         return ans;
    21     }
    22 };
    View Code

    LeetCode 1627. 带阈值的图连通性

    A和B, P为A,B的公因子, 连接P和A即可, 最后再判断,  用并查集处理即可

     1 class Solution {
     2 public:
     3     int fi(int x, vector<int>& fa) {
     4         return x == fa[x] ? x : fa[x] = fi(fa[x], fa);
     5     }
     6     vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) {
     7         vector<bool> ans;
     8         vector<int> fa(n + 1, 0);
     9         for (int i = 1; i <= n; i++) fa[i] = i;
    10         for (int i = threshold + 1; i <= n; i++) {
    11             for (int j = 2 * i; j <= n; j += i) {
    12                 int fx = fi(i, fa), fy = fi(j, fa);
    13                 if (fx != fy) fa[fx] = fy;    
    14             }
    15         }
    16         int m = queries.size();
    17         for (int i = 0; i < m; i++) {
    18             int fx = fi(queries[i][0], fa), fy = fi(queries[i][1], fa);
    19             ans.push_back(fx == fy);
    20         }
    21         return ans;
    22     }
    23 };
    View Code
  • 相关阅读:
    dfs手写栈模板
    Remember the Word
    Sockets
    Sanatorium
    Exams
    Cormen — The Best Friend Of a Man
    win 7 普通家庭版 装IIS
    [引]构造文法时表达式中算符优先级的问题
    Chart系列(二):数据绑定
    算法整理篇之:数据结构 | 数组(1)
  • 原文地址:https://www.cnblogs.com/pavtlly/p/13914906.html
Copyright © 2011-2022 走看看