Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1062245
  • 博文数量: 77
  • 博客积分: 821
  • 博客等级: 军士长
  • 技术积分: 1905
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-23 16:17
个人简介

学校:上海交通大学软件工程 学历:硕士 行业:从事流媒体移动开发 QQ: 412595942 邮箱:yiikai1987910@gmail.com

文章分类

全部博文(77)

文章存档

2016年(4)

2015年(15)

2014年(16)

2013年(12)

2012年(21)

2011年(9)

分类: C/C++

2015-02-25 13:21:19

     并查集的原理可以google 很多,比较简单。这里主要记录下自己的实现。
     一个典型的应用是在kruskal算法中
    直接上代码:
    

点击(此处)折叠或打开

  1. #define MAXN 7
  2. int ID[MAXN] = { 0 };
  3. int rank[MAXN];
  4. class union_find
  5. {
  6. public:
  7.     union_find();
  8.     int find_root(int x);
  9.     void connect(int x, int y);
  10.     bool isConnected(int x, int y);
  11. };

  12. bool union_find::isConnected(int x, int y)
  13. {
  14.     int xRoot = find_root(x);
  15.     int yRoot = find_root(y);
  16.     if (xRoot == yRoot)
  17.     {
  18.         printf("Has Connected\n");
  19.         return true;
  20.     }
  21.     else
  22.         return false;
  23. }


  24. union_find::union_find()
  25. {
  26.     for (int i = 0; i < MAXN; i++)
  27.     {
  28.         ID[i] = i;
  29.         rank[i] = 1;
  30.     }
  31. }

  32. int union_find::find_root(int x)
  33. {
  34.     if (ID[x] == x)
  35.         return x;
  36.     return find_root(ID[x]);
  37. }

  38. void union_find::connect(int x, int y)
  39. {
  40.     int xRoot = find_root(x);
  41.     int yRoot = find_root(y);
  42.     if (xRoot == yRoot)
  43.     {
  44.         printf("Has Connected\n");
  45.         return;
  46.     }
  47.     if (rank[xRoot] >= rank[yRoot])
  48.     {
  49.         rank[xRoot] += 1;
  50.         ID[yRoot] = ID[xRoot];
  51.     }
  52.     else
  53.     {
  54.         rank[yRoot] += 1;
  55.         ID[xRoot] = ID[yRoot];
  56.     }
  57. }


  58. int _tmain(int argc, _TCHAR* argv[])
  59. {
  60.     union_find m;
  61.     m.connect(ID[0], ID[1]);
  62.     m.connect(ID[2], ID[1]);
  63.     m.connect(ID[3], ID[4]);
  64.     if (m.isConnected(ID[3], ID[4]))
  65.     {
  66.         printf("connected\n");
  67.     }
  68.     return 0;
  69. }

阅读(1659) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~