[关闭]
@darkproject 2017-03-04T15:16:08.000000Z 字数 980 阅读 813

并查集与生成树专题

集训队


A - How Many Tables (hdu 1213)

确定人之间的关系,然后在一起♂,确定有多少组人一起♂

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<algorithm>
  4. using namespace std;
  5. int par[1005];
  6. int n, m, t;
  7. void init()
  8. {
  9. for (int i = 1; i <= n; i++)
  10. par[i] = i;
  11. }
  12. int find(int x)
  13. {
  14. if (par[x] == x)
  15. return x;
  16. else
  17. return par[x] = find(par[x]);
  18. }
  19. int main()
  20. {
  21. cin >> t;
  22. while (t--)
  23. {
  24. int a, b, ans = 0;
  25. cin >> n >> m;
  26. init();
  27. for (int i = 1; i <= m; i++)
  28. {
  29. int x, y;
  30. cin >> a >> b;
  31. x = find(a);
  32. y = find(b);
  33. if(x!=y)
  34. par[x] = y;
  35. }
  36. for (int i = 1; i <= n; i++)
  37. if (par[i] == i)
  38. ans++;
  39. cout << ans << endl;
  40. }
  41. return 0;
  42. }

B - Corporative Network poj1962

典型的带权并查集,I 连接2点,E确定此点离最终点距离(若无指向则为本身)

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <algorithm>
  4. const int maxn = 1e5;
  5. int par[maxn], d[maxn];
  6. int find(int x)
  7. {
  8. if (par[x] == x)
  9. return x;
  10. else {
  11. int temp = par[x];
  12. par[x] = find(par[x]);
  13. d[x] += d[temp];
  14. return par[x];
  15. }
  16. }
  17. int main()
  18. {
  19. int t;
  20. scanf("%d", &t);
  21. while (t--)
  22. {
  23. int n, a, b;
  24. char ch;
  25. scanf("%d", &n);
  26. for (int i = 0; i <= n; i++)
  27. {
  28. par[i] = i;
  29. d[i] = 0;
  30. }
  31. while (scanf(" %c",&ch),ch!='O')
  32. {
  33. if (ch == 'I')
  34. {
  35. scanf("%d %d", &a, &b);
  36. par[a] = b;
  37. d[a] = abs(a - b) % 1000;
  38. }
  39. else {
  40. scanf("%d", &a);
  41. find(a);
  42. printf("%d\n", d[a]);
  43. }
  44. }
  45. }
  46. return 0;
  47. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注