不相交集

《数据结构与算法分析——C语言描述》  第八章


disjset.h

#ifndef _DisjSet_H
#define _DisjSet_H
#define NumSets 22

typedef int DisjSet[NumSets + 1];//DisjSet为一个数组类型
typedef int SetType;
typedef int ElementType;

void initilialize_disjSet(DisjSet s);
void setUnion_disjSet(DisjSet s, SetType root1, SetType root2);
SetType find_disjSet(ElementType X, DisjSet s);

#endif


disjset.c

#include"disjset.h"

void initilialize_disjSet(DisjSet s) {
	for (int i = NumSets; i > 0; i--)
		s[i] = 0;
}

void setUnion_disjSet(DisjSet s, SetType root1, SetType root2) {
	if (s[root2] < s[root1]) {
		s[root1] = root2;
	}
	else {
		if (s[root2] == s[root1])
			s[root1]--;
		s[root2] = root1;
	}
}

SetType find_disjSet(ElementType X, DisjSet s) {
	if (s[X] <= 0)
		return X;
	else
		return s[X]= find_disjSet(s[X], s);
}


main.c

#include<stdio.h>
#include"disjset.h"


int main() {
	DisjSet s;
	initilialize_disjSet(s);
	int u, v;
	printf("enter the connection\n");
	
	while (scanf("%d%d", &u, &v) == 2) {
		SetType utype = find_disjSet(u, s);
		SetType ttype = find_disjSet(v, s);
		if (utype == ttype)
			printf("has connected\n");
		else {
			printf("conncet them\n");
			setUnion_disjSet(s, utype,ttype);
		}
		printf("enter the connection\n");
	}
}


你可能感兴趣的:(不相交集)