数据结构实验:连通分量个数

                                                                                                 数据结构实验:连通分量个数


Time Limit: 1000MS Memory Limit: 65536KB


Submit Statistic


Problem Description


在无向图中,如果从顶点vi到顶点vj有路径,则称vi和vj连通。如果图中任意两个顶点之间都连通,则称该图为连通图,
否则,称该图为非连通图,则其中的极大连通子图称为连通分量,这里所谓的极大是指子图中包含的顶点个数极大。


例如:一个无向图有5个顶点,1-3-5是连通的,2是连通的,4是连通的,则这个无向图有3个连通分量。


 


Input


第一行是一个整数T,表示有T组测试样例(0 < T <= 50)。每个测试样例开始一行包括两个整数N,M,(0 < N <= 20,0 <= M <= 200)
分别代表N个顶点,和M条边。下面的M行,每行有两个整数u,v,顶点u和顶点v相连。


Output


每行一个整数,连通分量个数。


Example Input


2
3 1
1 2
3 2
3 2
1 2


Example Output


2

1



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int pre[2333];
void initiliz(int n)
{
for(int i=0;i<=n;i++)
{
pre[i] = i;
}
}
int Find(int root)
{
int a = root;
while(pre[root]!=root)
{
root = pre[root];
}
while(pre[a]!=root)
{
int temp = pre[a];
pre[a] = root;
a = temp;
}
return root;
}
int Count(int n)
{
int count = 0;
for(int i=0;i<=n;i++)
{
int root = Find(i);
if(root)
{
count++;
pre[root] = 0;
}
}
return count;
}
void Join(int a,int b)
{
int root_a = Find(a);
int root_b = Find(b);
if(root_a!=root_b)
{
if(root_a<root_b)
{
pre[root_a] = root_b;
}
else
{
pre[root_b] = root_a;
}
}
}
int main()
{
int T,n,m,u,v;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&m,&n);
        initiliz(m);
while(n--)
{
scanf("%d%d",&u,&v);
Join(u,v);
}
printf("%d\n",Count(m));
}
return 0;
}

posted @ 2016-11-19 22:03  Philtell  阅读(209)  评论(0编辑  收藏  举报