티스토리 뷰

반응형

루트 노드 그 자체가 집합을 대표한다.



-----------------------------------------------------------------


1. DisjointSet.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef DISJOINTSET_H
#define DISJOINTSET_H
 
#include <stdio.h>
#include <stdlib.h>
 
typedef struct tagDisjointSet{
    struct tagDisjointSet* Parent;
    void* Data;
}DisjointSet;
 
void DS_UnionSet(DisjointSet* Set1,DisjointSet* Set2);
DisjointSet* DS_FindSet(DisjointSet* Set);
DisjointSet* DS_MakeSet(void* NewData);
void DS_DestroySet(DisjointSet* Set);
 
#endif
cs



2. DisjointSet.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "DisjointSet.h"
 
 
DisjointSet* DS_FindSet(DisjointSet* Set){
    while(Set->Parent!=NULL){
        Set=Set->Parent;
    }
    return Set;
}
 
void DS_UnionSet(DisjointSet* Set1,DisjointSet* Set2){
    Set2=DS_FindSet(Set2);
    Set2->Parent=Set1;
}
 
DisjointSet* DS_MakeSet(void* NewData){
    DisjointSet* NewNode=(DisjointSet*)malloc(sizeof(DisjointSet));
 
    NewNode->Data=NewData;
    NewNode->Parent=NULL;
 
    return NewNode;
}
 
void DS_DestroySet(DisjointSet* Set){
    free(Set);
}
 
 
cs



3. Test_DisjointSet.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "DisjointSet.h"
 
int main(){
    int a=1,b=2,c=3,d=4;
 
    DisjointSet* Set1=DS_MakeSet(&a);
    DisjointSet* Set2=DS_MakeSet(&b);
    DisjointSet* Set3=DS_MakeSet(&c);
    DisjointSet* Set4=DS_MakeSet(&d);
 
 
 
    // ( 1 ) ( 2 ) ( 3 ) ( 4 ) 
    printf("Set1==Set2 ? : %d\n",DS_FindSet(Set1)==DS_FindSet(Set2));
 
    DS_UnionSet(Set1,Set3); // ( 1 , 3 ) ( 2 ) ( 4 )
    printf("Set1==Set3 ? : %d\n",DS_FindSet(Set1)==DS_FindSet(Set3));
 
    DS_UnionSet(Set3,Set4); // ( 1 , 3 , 4 ) ( 2 )
    printf("Set3==Set4 ? : %d\n",DS_FindSet(Set3)==DS_FindSet(Set4));
 
    return 0;
}
cs



실행결과



반응형
댓글