zoukankan      html  css  js  c++  java
  • 并查集实现

      常可用来判断两个元素是否在同一个集合中,n^2的复杂度太大。

     1 #include <stdio.h>
     2 
     3 #define MAX 100
     4 int parent[MAX];
     5 
     6 int find(int x)
     7 {
     8     if(x<0||x>=MAX)
     9     {
    10         return -1;
    11     }
    12     if(parent[x]==x)
    13     {
    14         return parent[x];
    15     }else
    16     {
    17         return parent[x] = find(parent[x]);
    18     }
    19 }
    20 
    21 
    22 void init()
    23 {
    24     int i;
    25     for(i=0;i<MAX;i++)
    26     {
    27         parent[i] = i;
    28     }
    29 }
    30 
    31 void my_union(int i, int j)
    32 {
    33     if(i<0 || i>=MAX || j<0 || j>=MAX)
    34     {
    35         return ;
    36     }
    37     int px = find(i);
    38         int py = find(j);
    39         parent[px] = py;
    40 }
    41 
    42 int main()
    43 {
    44     int i;
    45     init();
    46     my_union(0, 1);
    47     for(i=0;i<10;i++)
    48     {
    49         printf("%d\n", find(i));
    50     }
    51     return 0;
    52 }
    53 /*
    54 秩的压缩,即总是把含孩子少的合并到孩子多的子树上。以减少不平衡树的产生。但是话说这个优化感觉有限。
    55 路径压缩。实际是记忆搜索或者伸展树的变种。
    56 */


     

  • 相关阅读:
    Subway POJ
    Invitation Cards POJ
    Cow Contest POJ
    MPI Maelstrom POJ
    Wormholes POJ
    Currency Exchange POJ
    Codeforces Round #608 (Div. 2) D Portals
    AcWing 1052. 设计密码
    AcWing 1058. 股票买卖 V 状态机模型dp
    AcWing 1057. 股票买卖 IV 状态机模型dp
  • 原文地址:https://www.cnblogs.com/hxsyl/p/3123643.html
Copyright © 2011-2022 走看看