集合的定義與查並操作

用的數據是:


數組下標: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;
}


發佈了62 篇原創文章 · 獲贊 17 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章