对于 How many tables 的一些的理解 这应该是我第一次写博客,也是刚接触ACM,正好刷到数据结构,就写一些自己的理解看法吧。 这道题应该是一道并查集的题,知识点在网上有特别生动有趣的讲解,建议可以看一下详细网站 因为这道题很简单,就不用说解题思路了吧,直接上代码了!
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>
#include <list>
#include <stack>
#include <sstream>
#include <cmath>
using namespace std;
int pre[ 1001 ] ;
int t[ 1001 ] ;
int Find ( int x)
{
int r;
r= x;
while ( pre[ r] != r)
{
r= pre[ r] ;
}
return r;
}
void join ( int x, int y)
{
int fx= Find ( x) ;
int fy= Find ( y) ;
if ( fx!= fy)
{
pre[ fx] = fy;
}
}
int main ( )
{
int T;
int N, M;
int n, m;
int sum;
cin>> T;
while ( T-- )
{
cin>> N>> M;
for ( int i= 1 ; i<= N; i++ )
{
pre[ i] = i;
}
for ( int i= 1 ; i<= M; i++ )
{
cin>> n>> m;
join ( n, m) ;
}
memset ( t, 0 , sizeof ( t) ) ;
for ( int i= 1 ; i<= N; i++ )
{
t[ Find ( i) ] = 1 ;
}
int i;
for ( sum= 0 , i= 1 ; i<= N; i++ )
{
if ( t[ i] )
{
sum++ ;
}
}
cout<< sum<< endl;
}
return 0 ;
}