ACM-并查集-How Many Tables

题目链接点击打开链接

附上代码:

#include<iostream>
using namespace std;
int tr[1010];
int find(int x)//寻找树根
{
 int r = x;
 while (r != tr[r])
 {
  r = tr[r];
 }
 return r;
}
int main()
{
 int t;
 cin >> t;
  while (t--)
  {
   int m, n,x,y;
   cin >> m >> n;
   for (int i = 1; i <= m; i++)tr[i] = i;
   for (int i = 0; i < n; i++)
   {
    cin >> x >> y;
    int fx, fy;
    fx = find(x);
    fy = find(y);
    if (fx != fy){ tr[fx] = fy; }
   }
   int count = 0;
   for (int i = 1; i <= m; i++)
   {
    if (tr[i] == i)count++;
   }
   cout << count << endl;
   cin.get();
   cin.get();
  }
}

猜你喜欢

转载自blog.csdn.net/qq_40783693/article/details/80395547