1. 程式人生 > >簡單合併並查集中的子集樹

簡單合併並查集中的子集樹

//此程式碼是資料結構的原始模板,可以剛接觸或考研時借鑑下,不適於刷題
#include<stdio.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
int nodenum;
int w=0;
typedef struct node
{
	int data;
	int parent;
}sqtree;
typedef struct code
{
   sqtree tree[100];
}bingcha,*bingchatree;
void initialization(bingchatree &ss,int elem[],int n)
{
	int i;
	nodenum=n;
	for(i=0;i<nodenum;i++)
	{
		ss->tree[i].data=elem[i];
		ss->tree[i].parent=-1;
	}
}
int find(bingchatree &ss,int x,int n)//x表示傳入結點的值
{
	int pos,i=0;
	for(i=0;i<n;i++)
	{
		if(x==ss->tree[i].data)
		{
			pos=i;
			break;
		}
	}
	if(pos<0||pos>=n)
	return -1;
	i=pos;
	while(ss->tree[i].parent>=0)
	i=ss->tree[i].parent;
	return i;
}
int merge(bingchatree &ss,int root1,int root2)//傳入合併結點頭結點的序號
{
	if(root1<0||root1>nodenum-1)return ERROR;
	if(root2<0||root2>nodenum-1)return ERROR;
	ss->tree[root2].parent=root1;//合併root2的結點到root1
	w++;
	return OK;
}
int main()
{
	int n,elem[100];
	printf("請輸入n個元素表示S中集合中元素的個數: ");
	scanf("%d",&n);
	printf("請輸入各元素的值: ");
	for(int i=0;i<n;i++)
	scanf("%d",&elem[i]);
    bingchatree ss;
	ss=(bingchatree)malloc(sizeof(bingcha));
	initialization(ss,elem,n);
	int x1,x2;
	printf("請輸入兩個SS中的子集s1,s2,併合並s2到s1: ");
	while(scanf("%d%d",&x1,&x2)!=EOF)
	{
	x1=find(ss,x1,n);//找出結點的頭結點的序號
	x2=find(ss,x2,n);
	printf("第一個結點的頭結點序號為%d 第二個結點的頭結點的序號為%d\n",x1,x2);
	if(x1==x2)
	{
		printf("此兩個結點子集是同一個子集,所以不能合併\n");
	}
	else
	{
	int x3=merge(ss,x1,x2);
	printf("%d\n",x3);
	}
	if((n-w)==1)
	{
		printf("ss中還剩最後一個子集,所以不能再合併請退出程式\n");
	}
	else
	{
	printf("並查集中還剩%d個子集\n",n-w);
	}
	}
	return  0;
}