CÀI ĐẶT TẬP HỢP BẰNG MẢNG
Cấu trúc dữ liệu
Code:
#define MaxLength 100
typedef char Set[MaxLength];
Khởi tạo tập hợp rỗng
Code:
void MakeNull(Set A) {
for(int i=0; i<MaxLength; i++)
A[i]=0;
}
Phép toán hợp (C = A hợp B)
Code:
void Union(Set A, Set B, Set C) {
for (int i=0; i<MaxLength; i++)
if ((A[i]==1)||(B[i]==1))
C[i]=1;
else
C[i]=0;
}
Phép toán giao (C = A giao B)
Code:
void Intersection(Set A,Set B, Set C) {
for (int i=0; i<MaxLength; i++)
if ((A[i]==1)&&(B[i]==1))
C[i]=1;
else
C[i]=0;
}
Phép toán hiệu (C=A\B)
Code:
void Difference(Set A, Set B, Set C) {
for (int i=0; i<MaxLength; i++)
if ((A[i]==1)&&(B[i]==1))
C[i]=0;
else
C[i]=A[i];
}
Hàm kiểm tra thành viên
Code:
char Member(int x, Set A) {
return A[x]==1;
}
Thêm phần tử x vào tập hợp A
Code:
void Insert(int x, Set A) {
A[x] = 1;
}
Xóa phần tử x trong tập hợp A
Code:
void Delete(int x, Set A) {
A[x] = 0;
}
Cho hai tập hợp bằng nhau
Code:
void Assign( Set A, Set B) {
for (int i=0; i<MaxLength; i++)
B[i] = A[i];
}
Tìm phần tử nhỏ nhất trong tập hợp
Code:
int Min(Set A){
int i = 0, Found = -1;
while(i<MaxLength && Found ==-1)
if(A[i]==1)
Found = i;
else
i++;
return Found;
}
Hàm kiểm tra hai tập hợp bằng nhau
Code:
char Equal(Set A, Set B) {
int i = 0, Found = 0;
while(i<MaxLength && Found == 0)
if(A[i] != B[i])
Found = 1;
else
i++;
return Found;
}
Nhập một tập hợp từ bàn phím
Code:
void Read(Set A) {
int x = 0;
printf("\nNhap den -1 thi ket thuc: ");
do {
scanf("%d",&x);
if(x!=-1)
A[x] = 1;
}while(x!=-1);
}
Xuất tập hợp ra màn hình
Code:
void Write(Set A) {
for (int i=0; i<MaxLength; i++)
if(A[i]==1)
printf("%3d",i);
}