HDU1213直接并查集

HDU1213直接并查集
http://acm.hdu.edu.cn/showproblem.php?pid=1213

刚睡觉起来,一不注意把parent初始化为0了,惭愧呀。。。
#include  < iostream >

using   namespace  std;

const   int  M = 1001 ;
int  parent[M];
int  uffind( int  i)
{
    
int  j,temp;
    
for (j = i;parent[i] >= 0 ;i = parent[i]);
    
while (j != i)
    {
        temp
= parent[j];
        parent[j]
= i;
        j
= temp;
    }
    
return  i;
}

void  ufunion( int  i, int  j)
{
    
int  temp;
    i
= uffind(i);
    j
= uffind(j);
    
if (i == j)
        
return ;
    temp
= parent[i] + parent[j];
    
if (parent[i] <= parent[j])
    {
        parent[i]
= temp;
        parent[j]
= i;
    }
    
else
    {
        parent[j]
= temp;
        parent[i]
= j;
    }
}

int  main()
{
    
int  t,m,n,i,j,res;
    cin
>> t;
    
while (t -- )
    {
        memset(parent,
- 1 , sizeof (parent));
        res
= 0 ;
        cin
>> n >> m;
        
while (m -- )
        {
            cin
>> i >> j;
            ufunion(i,j);
        }
        
for (i = 1 ;i <= n;i ++ )
            
if (parent[i] < 0 )
                res
++ ;
        cout
<< res << endl;
    }
    
return   0 ;
}


你可能感兴趣的:(HDU1213直接并查集)