原题链接:click here
这是一题并查集的水题,是我第一次用并查集做出来的题目。请各位原谅我吧,让我小小的yy下。
没什么可说的,直接贴代码:
#include<stdio.h>
#define MAX 1001
int father[MAX];
/*初始化数组*/
void make_set(int n)
{
int i;
for(i=1;i<=n;i++)
father[i]=i;
}
/*查找x的父节点*/
int find_set(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
/*通过x与y的父节点判断x与y有没有关系,如果没关系,则把y的父节点变成x父节点的子节点,这样它们就拥有了共同的祖先,即在同一个集合中。如此就完成了两个集合的并*/
void union_set(int x,int y)
{
while(x!=father[x])
x=father[x];
while(y!=father[y])
y=father[y];
if(x!=y)
father[x]=y;
}
int main()
{
int t,n,m;
int j,k,l,count;
scanf("%d",&t);
while(t--)
{
count=0;
scanf("%d%d",&n,&m);
make_set(n);//初始化
while(m--)
{
scanf("%d%d",&j,&k);
union_set(j,k);//如果j和k有关系,则执行联合操作
}
for(l=1;l<=n;l++)
if(father[l]==l)count++;//统计最终的集合个数
printf("%d\n",count);
}
return 0;
}
#i#include<stdio.h>
#define MAX 1005
int father[MAX];
void make_set(int n)
{
int i;
for(i=1;i<=n;i++)
father[i]=i;
}
int find_set(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
void union_set(int x,int y)
{
while(x!=father[x])
x=father[x];
while(y!=father[y])
y=father[y];
if(x!=y)
father[x]=y;
}
int main()
{
int t,n,m;
int j,k,l,count;
scanf("%d",&t);
while(t--)
{
count=0;
scanf("%d%d",&n,&m);
make_set(n);
while(m--)
{
scanf("%d%d",&j,&k);
union_set(j,k);
}
for(l=1;l<=n;l++)
if(father[l]==l)count++;
printf("%d\n",count);
}
return 0;
}nclude<stdio.h>
#define MAX 1005
int father[MAX];
void make_set(int n)
{#include<stdio.h>
#define MAX 1005
int father[MAX];
void make_set(int n)
{
int i;
for(i=1;i<=n;i++)
father[i]=i;
}
int find_set(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
void union_set(int x,int y)
{
while(x!=father[x])
x=father[x];
while(y!=father[y])
y=father[y];
if(x!=y)
father[x]=y;
}
int main()
{
int t,n,m;
int j,k,l,count;
scanf("%d",&t);
while(t--)
{
count=0;
scanf("%d%d",&n,&m);
make_set(n);
while(m--)
{
scanf("%d%d",&j,&k);
union_set(j,k);
}
for(l=1;l<=n;l++)
if(father[l]==l)count++;
printf("%d\n",count);
}
return 0;
}
int i;
for(i=1;i<=n;i++)
father[i]=i;
}
int find_set(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
void union_set(int x,int y)
{
while(x!=father[x])
x=father[x];
while(y!=father[y])
y=father[y];
if(x!=y)
father[x]=y;
}
int main()
{
int t,n,m;
int j,k,l,count;
scanf("%d",&t);
while(t--)
{
count=0;
scanf("%d%d",&n,&m);
make_set(n);
while(m--)
{
scanf("%d%d",&j,&k);
union_set(j,k);
}
for(l=1;l<=n;l++)
if(father[l]==l)count++;
printf("%d\n",count);
}
return 0;
}#include<stdio.h>
#define MAX 1005
int father[MAX];
void make_set(int n)
{
int i;
for(i=1;i<=n;i++)
father[i]=i;
}
int find_set(int x)
{
while(x!=father[x])
x=father[x];
return x;
}
void union_set(int x,int y)
{
while(x!=father[x])
x=father[x];
while(y!=father[y])
y=father[y];
if(x!=y)
father[x]=y;
}
int main()
{
int t,n,m;
int j,k,l,count;
scanf("%d",&t);
while(t--)
{
count=0;
scanf("%d%d",&n,&m);
make_set(n);
while(m--)
{
scanf("%d%d",&j,&k);
union_set(j,k);
}
for(l=1;l<=n;l++)
if(father[l]==l)count++;
printf("%d\n",count);
}
return 0;
}