集合的定义与查并操作

用的数据是:


数组下标:0  1  2  3  4  5  6  7  8  9

data:        1  2  3  4  5  6  7  8  9  10

parent:   -2  3  0 -2  0 -3  3  5  5   5


#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;

typedef struct {
	int data;/*数组中的值*/
	int parent;/*代表当前这个值(data)的根结点上的值(data)的数组下标*/
}SetType;

const int MAX = 10;

int Find(SetType S[],int X)
{
	int i = 0;
	for(;i < MAX && S[i].data !=X; i++);
	
	for(;S[i].parent >= 0; i = S[i].parent);
	
	return i;
}

void Union(SetType S[],int root1,int root2)
{
	if(S[root2].parent < S[root1].parent)
	{
		S[root2].parent += S[root1].parent;
		S[root1].parent = root2;
	}
	else
	{
		S[root1].parent += S[root2].parent;
		S[root2].parent = root1;
	}
	
}

int main(void)
{
	SetType S[10];
	int root1,root2;
	int parent;
	
	for(int i = 0; i < 10; i++)
	{
		S[i].data = i+1;
		scanf("%d",&parent);
		S[i].parent = parent;
	}
	
	root1 = Find(S,3);
	root2 = Find(S,9);
	
	printf("root1 = %d root2 = %d\n\n",root1,root2);
	Union(S,root1,root2);
	
	printf("S[0].parent = %d S[5].parent = %d",S[0].parent,S[5].parent);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值