Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. // 并查集数据结构
  2. // 对动态连接图可能的操作
  3. // 1) 查询节点属于的组
  4. // 2)判断两个节点是否属于同一个组
  5. // 3)连接两个节点,使之属于同一个组
  6. // 4)获取组的数目
  7.  
  8. // 树数据结构容易出现极端情况,在建树的过程中,树的最终形态严重依赖于输入数据本身的性质
  9.  
  10.  
  11. // 判断一个无向图是树的条件是连通图,且所有点的入度小于等于1
  12.  
  13. // 并查集的实现
  14.  
  15. #include <memory.h>
  16. #include <iostream>
  17. #include <stdio.h>
  18. using namespace std;
  19.  
  20.  
  21. class UF
  22. {
  23. private:
  24. int * id;// 保存其父节点,当是root节点时 id[p] = p;
  25. int count; // 组个数
  26. int * sz;
  27.  
  28. public:
  29. UF(int n)
  30. {
  31. id = new int [n];
  32. for(int i=0; i< n; i++)
  33. id[i] = i;
  34. sz = new int [n];
  35. for(int i=0; i< n; i++)
  36. sz[i] = 1;
  37. count = n;
  38. }
  39.  
  40. // 返回组的个数
  41. int Count()
  42. {
  43. return count;
  44. }
  45.  
  46. // 判断是否连通
  47. bool is_connected(int p, int q)
  48. {
  49. return find(p) == find(q);
  50. }
  51.  
  52. // find 查找节点的组ID
  53. int find(int p)
  54. {
  55. while(p != id[p])
  56. {
  57. id[p] = id[id[p]];
  58. p = id[p];
  59. }
  60. return p;
  61. }
  62.  
  63. // 合并连接两个组
  64. void Union(int p, int q)
  65. {
  66. int pRoot = find(p);
  67. int qRoot = find(q);
  68. //cout << "pRoot " <<pRoot << "\t" << "qRoot " << qRoot <<
  69. // endl;
  70.  
  71. if(pRoot == qRoot)
  72. return;
  73.  
  74. // 将小树作为大树的子树
  75. if (sz[pRoot] < sz[qRoot])
  76. {
  77. id[pRoot] = qRoot;
  78. sz[qRoot] += sz[pRoot];
  79. }
  80. else
  81. {
  82. id[qRoot] = pRoot;
  83. sz[pRoot] += sz[qRoot];
  84. }
  85. count --;
  86. }
  87.  
  88. };
  89.  
  90.  
  91. int main()
  92. {
  93. //freopen("hiho_1322.data","r",stdin);
  94. int t;
  95. cin >>t;
  96. for(int i=0; i< t;i++)
  97. {
  98.  
  99. int N, M;
  100. cin >> N >> M;
  101. UF uf(N);
  102. int * in = new int[N];
  103. memset(in,0,sizeof(int) * N);
  104. bool is_tree = true;
  105. for(int k = 0; k < M; k++)
  106. {
  107. int s,e;
  108. cin >> s >> e;
  109. uf.Union(s-1,e-1);
  110. in[e-1] ++;
  111. if (in[e-1] > 1)
  112. is_tree = false;
  113.  
  114. }
  115. if (uf.Count() > 1)
  116. is_tree = false;
  117. if (is_tree)
  118. cout << "YES" << endl;
  119. else
  120. cout << "NO" << endl;
  121. }
  122. return 0;
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement