如果有10台电脑{1,2,3,4,...,9,10},已知下列电脑之间实现了连接:
1和2,2和4,3和5,4和7,5和8,6和9,6和10
问:2和7,5和9之间是否可以连通?
效果:
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct data
{
int num;
int parent;
}data;
typedef struct gather
{
data* info[30];
int size;
}gather;
gather* establishgather(gather* p);
int findroot(data* p, int a);
void uni(data* p);
void judge(gather*p);
int main()
{
gather* p = (gather*)malloc(sizeof(gather));
p = establishgather(p);
uni(p);
judge(p);
judge(p);
}
gather* establishgather(gather* p)
{
int i;
int number = 0;
printf("please enter the num you want to insert the gather,and 999 means end\n");
for ( i=0;; i++)
{
scanf("%d", &number);
if (number==999)
{
printf("the gather is estabilshed\n");
break;
}
else
{
p->info[i] = (data*)malloc(sizeof(data));
p->info[i]->num = number;
p->info[i]->parent = -1;
}
}
p->size = i - 1;
return p;
}
int findroot(gather*p, int a)
{
int i;
for ( i = 0; i <= p->size; i++)
{
if (p->info[i]->num==a)
{
while (p->info[i]->parent>=0)
{
i = p->info[i]->parent ;
}
return i;
}
}
printf("the data is not in the gather\n");
return -1;
}
void uni(gather*p)
{
int a = -999;
int b = -999;
printf("please enter the data you want to union, -1 means end\n");
while (1)
{
scanf("%d %d", &a, &b);
if (a==-1 || b==-1)
{
break;
}
int roota, rootb;
roota = findroot(p, a);
rootb = findroot(p, b);
p->info[rootb]->parent = roota;
}
return p;
}
void judge(gather*p)
{
int a, b, roota, rootb;
printf("please enter the numbers you wang to judge if they are in the same gather\n");
scanf("%d %d", &a, &b);
roota = findroot(p, a);
rootb = findroot(p, b);
if (roota==rootb)
{
printf("they are in the same gather\n");
}
else
{
printf("they are not in the same gather\n");
}
return 0;
}