간단하게 합 쳐 집 중 된 부분 집합 트 리 를 찾 습 니 다.

//             ,            ,     
#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
",x1,x2); if(x1==x2) { printf(" ,
"); } else { int x3=merge(ss,x1,x2); printf("%d
",x3); } if((n-w)==1) { printf("ss ,
"); } else { printf(" %d
",n-w); } } return 0; }

좋은 웹페이지 즐겨찾기