用c语言编写:设二元关系A={1,2,3,4},R={<1,1>,<2,2>,<2,3>,<3,1>,<3,3>,<3,4>,<4,2><4,4>},编程判断 R 是否是等价关系。如果是,求其商集。
时间: 2024-05-31 20:08:33 浏览: 118
#include <stdio.h>
#define MAX 100
int main()
{
int A[] = {1, 2, 3, 4}; //定义集合A
int R[][2] = {{1,1},{2,2},{2,3},{3,1},{3,3},{3,4},{4,2},{4,4}}; //定义关系R
int n = sizeof(A) / sizeof(int); //集合A的元素个数
int m = sizeof(R) / sizeof(R[0]); //关系R的元素个数
int i, j, k;
int reflexive = 0, symmetric = 0, transitive = 0; //判断是否为自反、对称、传递关系的标志
int eqclass[MAX][MAX], cnt[MAX], num = 0; //eqclass存储商集,cnt存储每个等价类的元素个数,num为等价类个数
//判断是否为自反关系
for (i = 0; i < n; i++) {
reflexive = 0;
for (j = 0; j < m; j++) {
if (A[i] == R[j][0] && A[i] == R[j][1]) {
reflexive = 1;
break;
}
}
if (!reflexive) break;
}
if (!reflexive) {
printf("R is not a reflexive relation.\n");
return 0;
}
//判断是否为对称关系
for (i = 0; i < m; i++) {
symmetric = 0;
for (j = 0; j < m; j++) {
if (R[i][0] == R[j][1] && R[i][1] == R[j][0]) {
symmetric = 1;
break;
}
}
if (!symmetric) break;
}
if (!symmetric) {
printf("R is not a symmetric relation.\n");
return 0;
}
//判断是否为传递关系
for (i = 0; i < m; i++) {
transitive = 0;
for (j = 0; j < m; j++) {
if (R[i][1] == R[j][0]) {
for (k = 0; k < m; k++) {
if (R[i][0] == R[k][0] && R[j][1] == R[k][1]) {
transitive = 1;
break;
}
}
if (transitive) break;
}
}
if (!transitive) break;
}
if (!transitive) {
printf("R is not a transitive relation.\n");
return 0;
}
//求商集
for (i = 0; i < n; i++) {
cnt[i] = 0;
for (j = 0; j < n; j++) {
eqclass[i][j] = 0;
}
}
for (i = 0; i < n; i++) {
int flag = 0;
for (j = 0; j < num; j++) {
if (eqclass[j][0] == A[i]) {
eqclass[j][cnt[j]] = A[i];
cnt[j]++;
flag = 1;
break;
}
}
if (!flag) {
eqclass[num][0] = A[i];
eqclass[num][cnt[num]] = A[i];
cnt[num]++;
num++;
}
for (j = i + 1; j < n; j++) {
int related = 0;
for (k = 0; k < m; k++) {
if (A[i] == R[k][0] && A[j] == R[k][1]) {
related = 1;
break;
}
}
if (related) {
flag = 0;
for (k = 0; k < num; k++) {
if (eqclass[k][0] == A[i]) {
eqclass[k][cnt[k]] = A[j];
cnt[k]++;
flag = 1;
break;
}
if (eqclass[k][0] == A[j]) {
eqclass[k][cnt[k]] = A[i];
cnt[k]++;
flag = 1;
break;
}
}
if (!flag) {
eqclass[num][0] = A[i];
eqclass[num][cnt[num]] = A[i];
cnt[num]++;
eqclass[num][cnt[num]] = A[j];
cnt[num]++;
num++;
}
}
}
}
//输出商集
printf("The equivalence classes are:\n");
for (i = 0; i < num; i++) {
printf("{ ");
for (j = 0; j < cnt[i]; j++) {
printf("%d ", eqclass[i][j]);
}
printf("}\n");
}
return 0;
}
阅读全文