Chinaunix首页 | 论坛 | 博客
  • 博客访问: 343098
  • 博文数量: 63
  • 博客积分: 1412
  • 博客等级: 中尉
  • 技术积分: 648
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-10 23:07
文章分类

全部博文(63)

文章存档

2012年(42)

2011年(21)

我的朋友

分类: C/C++

2012-03-11 16:54:38

今天看了下并查集运算。
并查集运算是用来操作集合的。它包含以下几个操作:
初始化:用于初始化并查集。
并运算:将2个集合合并
查运算:查找一个元素的父节点。
 

点击(此处)折叠或打开

  1. /*
  2.  *    并查集
  3.  */

  4. /*
  5.  * 将节点的父节点设置成自己
  6.  */
  7. #include <iostream>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <stdlib.h>

  11. #define MAX 100
  12. int    father[MAX];

  13. #define ILLEGAL( x, n ) ( x<0 || x > n )

  14. void set_init( int n )
  15. {
  16.     int i = 0;

  17.     for( i=0; i<n; i++ )
  18.     {
  19.         father[i] = i;
  20.     }
  21. }

  22. /*
  23.  * 查找x的父节点
  24.  */

  25. int set_find( int x )
  26. {
  27.     return father[x];
  28. }

  29. /*
  30.  * 将x所在集合与y所在集合合并
  31.  */

  32. int set_union( int x, int y, int n )
  33. {
  34.     if( ILLEGAL(x,n) )
  35.     {
  36.         return 1;
  37.     }
  38.     if( ILLEGAL(y,n) )
  39.     {
  40.         return 1;
  41.     }

  42.     int father_x = 0;
  43.     int father_y = 0;
  44.     int father_i = 0;

  45.     father_x = set_find( x );
  46.     father_y = set_find( y );

  47.     for( int i=0; i<n; i++ )    
  48.     {
  49.         father_i = father[i];
  50.         if( father_i == father_x )
  51.         {
  52.             father[i] = father_y;
  53.         }
  54.     }
  55. }

  56. void set_print( int n )
  57. {
  58.     for( int i=0; i<n; i++ )
  59.     {
  60.         printf( "%d ", father[i] );
  61.     }
  62.     printf( "\n" );
  63. }

  64. int    main()
  65. {
  66.     int n = 0;
  67.     int x = 0;
  68.     int y = 0;

  69.     scanf( "%d", &n );

  70.     set_init( n );
  71.     set_print( n );

  72.     for( int i=0; i<5; i++ )
  73.     {
  74.         printf( "input x, y\n" );
  75.         scanf( "%d", &x );
  76.         scanf( "%d", &y );

  77.         set_union( x, y, n );
  78.         set_print( n );
  79.         printf( "end\n\n" );
  80.     }

  81. }

阅读(1143) | 评论(0) | 转发(0) |
0

上一篇:剪枝算法

下一篇:c static 变量

给主人留下些什么吧!~~