How Many Tables HDU - 1213

版权声明: https://blog.csdn.net/weixin_40959045/article/details/88381994

每次在不同集合相连减一

#include <bits/stdc++.h>
 
 using namespace std;
 #define MAX_LENGTH 1005
 int Unions[MAX_LENGTH];
 void init_QucikUnion(int length){
   for (int i = 0;i<=length;i++){
     Unions[i]= i;
   }
 }
 int Find(int n){
   while (Unions[n] != n)
     n = Unions[n] ;
   return n;
 }
 void Union(int i,int j){
   Unions[Find(j)] = Find(i);
 }
 
 int main()
 {
   int T;
   int N,M;
   scanf("%d",&T);
   while (T-- >0){
     scanf("%d%d",&N,&M);
     init_QucikUnion(N);
     int tables = N;
     for (int i = 0;i<M;i++){
       int u,v;
       scanf("%d%d",&u,&v);
       if (Find(u) != Find(v)){
         Union(u,v);
         tables--;
       }
     }
     printf("%d\n",tables);
   }
     return 0;
 }

猜你喜欢

转载自blog.csdn.net/weixin_40959045/article/details/88381994
今日推荐