用的数据是:
数组下标: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;
}